8.数字处理类

8.1数字格式化

java的数字格式化操作主要针对浮点数

java数据绝对值在10^3到10^7之间,将以常规形式显示,否则用科学记数法表示

显然以上表示方法不能满足现实需求,故java提供DecimalFormat类进行格式化操作

使用步骤:给实例化对象提供模式化模板(实例化时提供或者后来提供均可),通过对象调用format()方法即可格式化数据

符号位置本地化?含义
0数字阿拉伯数字
#数字字阿拉伯数字,如果不存在则显示为空
.数字小数分隔符或货币小数分隔符
-数字减号
,数字分组分隔符
E数字分隔科学计数法中的尾数和指数。在前缀或后缀中无需加引号。
;子模式边界分隔正数和负数子模式
%前缀或后缀乘以 100 并显示为百分数
/u2030前缀或后缀乘以 1000 并显示为千分数
¤ (/u00A4)前缀或后缀货币记号,由货币符号替换。如果两个同时出现,则用国际货币符号替换。如果出现在某个模式中,则使用货币小数分隔符,而不使用小数分隔符。
'前缀或后缀用于在前缀或或后缀中为特殊字符加引号,例如 "'#'#" 将 123 格式化为 "#123"。要创建单引号本身,请连续使用两个单引号:"# o''clock"

举例一:

该实例定义了两个静态方法,前者在实例化时提供模板,后者先实例化,而后调用applyPattern()方法提供模板

import java.text.DecimalFormat;
//利用import关键字导入类包,否则编译器无法识别DecimalFormat
public class Decimal {
    static public void SimpleFormat(String pattern,double value) {      
        //String参数提供格式化模板,dobule参数提供被格式化数据
        DecimalFormat myFormat=new DecimalFormat(pattern);
        //在实例化DecimalFormat类时,提供参数
        String output=myFormat.format(value);
        //通过对象调用format()方法,格式化数据,并返回一个String类
        System.out.println(output+" "+pattern+" "+value);
    }

    static public void FormatApplyPatternText(String pattern,double value) {
        //该方法和SimpleFormat()方法等价,区别在于本方法是先实例化对象,再设置格式化模板
        DecimalFormat myFormat=new DecimalFormat();
        myFormat.applyPattern(pattern);
        //实例化对象后,通过对象调用applyPattern()方法,设置格式化模板
        String output=myFormat.format(value);
        System.out.println(output+" "+pattern+" "+value);
    }

    public static void main(String[] args) {
        SimpleFormat("#,###.##kg",12345678.12345);
        FormatApplyPatternText("0.##",0.678);
                //经测试,整数部分无论设置多少个#、0均会显示全部显示,而小数部分则根据模板的小数部分位数四舍五入
        SimpleFormat("#.###%",12.078511);
        //将数据以百分号形式显示,小数点后保留3位
        FormatApplyPatternText("##.###\u2030", 0.00056442);
        //将数据以千分号形式显示,小数点后保留3位
        SimpleFormat("#.##\u00A4",543.21);
        //"\u00A4"为货币符号
    }
}

点击并拖拽以移动

举例二:

不需要多次格式化数据时,可以直接在主函数中新建对象并调用format()方法

        String output1=new DecimalFormat("#.##kg").format(13.234);      
        //1.此时new出来的该对象不可以再次使用
        DecimalFormat myFormat=new DecimalFormat("#.##%");
        String output2=myFormat.format(12.345);     
        myFormat.applyPattern("#.##");
        String output3=myFormat.format(567.789);
        //2.带引用的对象,此时模板格式可以再次更改
        System.out.println(output2);
        System.out.println(output1);
        System.out.println(output3);

举例三:

不设置格式化模板时,亦可以通过其他方法修改数据格式

        DecimalFormat myFormat = new DecimalFormat();
        myFormat.setGroupingSize(2);
        String output1 = myFormat.format(123456.789);
        // 此时整数部分将以间隔为2进行分组
        myFormat.setGroupingUsed(false);
        // 此时分组操作被关闭,将不再进行划分
        String output2 = myFormat.format(123456.789);
        System.out.println(output1);
        System.out.println(output2);

点击并拖拽以移动

8.2Math类

Math类提供了众多静态数学方法,直接通过“Math.数学方法”调用即可

Math类同样也提供了一些数学常量,如:Math.PI 和 Math.E

1.三角函数方法

public static double sin(double a);

public static double cos(double a);

public static double tan(double a);

public static double asin(double a);//反正弦

public static double acos(double a);

public static double atan(double a);

public static double toRadians(double angdeg);//角度转弧度

public static double toDegress(double angrad);//弧度转角度

举例如下:

    System.out.println("90度角度正弦"+Math.sin(Math.PI/2));
    System.out.println("约90度角度正弦"+Math.sin(3.1415926/2));
    System.out.println("二分之根号二的反正弦"+Math.asin(Math.sqrt(2)/2));
    //若再利用Math.Degrees()方法,可知二分之根号反正弦角度制度数为45度
    System.out.println("1的反正切值"+Math.atan(1));
    //若再利用Math.Degrees()方法,可知1的反正切值角度制度数为45度
    System.out.println("120度角度弧度值"+Math.toRadians(120.0));
    System.out.println("二分之pi度角度值"+Math.toDegrees(Math.PI/2));
2.指数函数方法

public static double exp(double a);//e^a

public static double log(double a);

public static double log10(double a);

public static double sqrt(double a);//非负数a的平方根

public static double cbrt(double a);//a的立方根

public static double pow(double a,double b);//a^b

举例如下:

System.out.println("e的3次方"+Math.exp(3));
System.out.println("ln(10)"+Math.log(10));
System.out.println("lng10(10)"+Math.log10(10));
System.out.println("根号二"+Math.sqrt(2));
System.out.println("-8的立方根"+Math.cbrt(-8));
System.out.println("2的-3次方"+Math.pow(2,-3));
3.取整函数方法

public static double ceil(double a);//返回大于或等于a的最小整数

public static double floor(double a);

public static double rint(double a);//返回与参数最接近整数,偶数优先

public static int round(float a);//参数加上0.5后,返回与参数最接近整数

public static long round(double a);//参数加上0.5后,返回与参数最接近整数,并强制转换为长整型

举例如下:

System.out.println(Math.ceil(3.55));
System.out.println(Math.floor(3.55));
System.out.println(Math.rint(3.5));
System.out.println(Math.round(3.5));
4.取最大值、最小值、绝对值函数

public static type max(type a,type b);

public static type min(type a ,type b);

public static type abs(type a);

举例如下:

System.out.println(Math.max(4, 8));
System.out.println(Math.min(4.0, 8.0));
System.out.println(Math.abs(-3.5));

8.3随机数

Java提供两种机制实现伪随机数,一种是Math类中的random()方法,另一种是Random类

1.Math.random()方法

该类将产生一个大于等于0小于1的double类型的随机数,稍作处理即可产生任意范围的随机数

举例如下:

        //产生num1至mun2之间的整数
    int num1=10;
    int num2=32;
    //若将num1、num2定义为double类型,此时将可能产生低于num1的值
    int num3=num1+(int)(Math.random()*(num2-num1+1));
    System.out.println(num1+"至"+num2+"的任意字符: "+num3);
    //产生ch1至ch2之间的字符
    char ch1='a';
    char ch2='z';
    char ch3=(char)(ch1+(Math.random()*(ch2-ch1+1)));
    System.out.println(ch1+"至"+ch2+"的任意字符: "+ch3);
2.Random类

java.util.Random类,可以通过实例化一个Random对象创建一个随机数生成器。

语法如下:

Random r=new Random(seedValue);
//seedValue是随机数生成器的种子,long类型,随机算法起源数字,与随机数区间无关;
Random r=new Random();
//若不提供种子,编译器将以当前时间作为随机数生成器种子,此时若运行速度过快,可能产生相同随机数

相关方法如下:

public void setSeed(long seedValue);//重设随机数种子

public int nextInt();//返回一个随机整数

public int nextInt(int n);//返回一个[0,n)区间内的的整数

public long nextLong(int n);//返回一个随机长整型整数

public boolean nextBoolean();//返回一个随机布尔数值

public float nextFloat();//返回一个[0,1.0)区间内的单精度浮点数

public double nextDouble();//返回一个[0,1.0)区间内的双精度浮点数

public double nextGaussian();//返回一个概率密度为高斯分布的双精度值

举例如下:

        Random r = new Random();
        double d1 = r.nextDouble() * 2.5 + 1;
        // 1.生成区间[1,3.5)内的小数

        int n1 = r.nextInt(10);
        int n2 = Math.abs(r.nextInt() % 10);
        // 2.生成区间[0,10)内的整数

        int n3 = r.nextInt(11);
        int n4 = Math.abs(r.nextInt() % 11);
        // 3.生成区间[0,10]内的整数

        int n5 = r.nextInt(18) - 3;
        int n6 = Math.abs(r.nextInt() % 18) - 3;
        // 4.生成区间[-3,15)内的整数

        Random r1 = new Random(10);
        Random r2 = new Random(10);
        for (int i = 0; i < 2; i++) {
            System.out.println(r1.nextInt());
            System.out.println(r2.nextInt());
        }
        // 5.证明相同种子的对象相同次数生成的随机数相同

        int n7 = r.nextInt(20);
        int m1;
        if (n6 < 11) {
            m1 = 1;
        } else if (n6 < 19) {
            m1 = 2;
        } else {
            m1 = 3;
        }
        // 6.概率控制,随机生成一个整数,55%为1,40%为2,5%为3
        // 6.概率控制,随机生成一个整数,55%为1,40%为2,5%为3

8.4大数字运算

1.BigInteger简介

java.math.BigInteger类可以准确表示任何大小的整数值,并封装了加减乘除、求绝对值、最大公约数、判断是或否为质数等操作。

常用构造方法:

public BigInteger(String val)

常用方法如下:

基本操作:
public BigInteger add(BigInteger val);//返回两个大整数的和
public BigInteger subtract(BigInteger val);//返回两个大整数相减的结果
public BigInteger divide(BigInteger val);// 返回两个大整数的商
public BigInteger multiply(BigInteger val);// 返回两个大整数的积
public BigInteger mod(BigInteger val);// 用当前大整数对val求模
public BigInteger remainder(BigInteger val);// 返回当前大整数除以val的余数
public biginteger[] divideAndReminder(BigInteger val);//
位操作:
public BigInteger not() ;// 返回当前大整数的非
public BigInteger and(BigInteger val);// 返回两个大整数的按位与的结果
public BigInteger andNot(BigInteger val);//返回两个大整数与非的结果
public BigInteger xor(BigInteger val);// 返回两个大整数的异或
public BigInteger or(BigInteger val);// 返回两个大整数的按位或
public BigInteger leftShift(int n) ;//将当前大整数左移n位后返回
public BigInteger rightShift(int n) ;// 将当前大整数右移n位后返回
类型转换:
public int intValue() ;//返回大整数的整型值
public long longValue() ;//返回大整数的long型值
public double doubleValue();// 返回大整数的double类型的值
public float floatValue();// 返回大整数的float类型的值

public byte[] toByteArray(BigInteger val);//将大整数转换成二进制反码保存在byte数组中
public String toString();//将当前大整数转换成十进制的字符串形式
其他操作:
public BigInteger abs();// 返回大整数的绝对值
public BigInteger negate();//返回当前大整数的相反数
public BigInteger gcd(BigInteger val) ;//返回大整数的最大公约数
public BigInteger max(BigInteger val);//返回两个大整数的最大者
public BigInteger min(BigInteger val);//返回两个大整数的最小者

public BigInteger pow(int exponent);//返回当前大整数的exponent次方

举例如下:

        BigInteger bigInstance = new BigInteger("2222222");
        System.out.println(bigInstance.multiply(new BigInteger("33333333")));
        // 乘法示例
        System.out.println(bigInstance.negate());
        // 取相反数示例
        System.out.println(bigInstance.divideAndRemainder(new BigInteger("33"))[0]);
        // 求商,注意该方法返回值是一个数组,第一个值时商,第二个值是余数
        System.out.println(bigInstance.divideAndRemainder(new BigInteger("33"))[1]);
        // 求余

点击并拖拽以移动

2.BigDecimal

java.math.BigDecimal类,比BigInteger多了小数的概念,支持任意精度浮点数,可以在商业中用来精确计算货币值。

初始化:

public BigDecimal(double val);//不推荐,可能得不到精确值

public BigDecimal(String val);

static BigDecimal valueOf(double d);//推荐,double(float)类型转BigDecimal常用

基本操作:

public BigDecimal add(BigDecimal augend);//加法

public BigDecimal subtract(BigDecimal subtrahend);//减法

public BigDecimal multiply(BigDecimal multiplicand)://乘法

public BigDecimal divide(BigDecimal divisor,int scale, int roundingMode):

//除法,三个参数分别表示除数、商的小数部分位数、近似处理模式

import java.math.BigDecimal;
public class BigDecimalDemo {
    static final int location=10;
public static void main(String[] args) {
BigDecimalDemo b=new BigDecimalDemo();
System.out.println(b.div(10,2));
}

public BigDecimal div(double value1,double value2) {
    return div(value1,value2,location);
}

//@SuppressWarnings("deprecation")
private BigDecimal div(double value1, double value2, int b) {
    if(b<0)System.out.println("b的值必须大于等于0");
    BigDecimal b1=new BigDecimal(Double.toString(value1));
    BigDecimal b2=new BigDecimal(Double.toString(value2));
    return b1.divide(b2,b,BigDecimal.ROUND_DOWN);
}
}

点击并拖拽以移动

参考资料:

http://www.jb51.net/article/83028.htm

https://www.jianshu.com/p/8b89ab19db84

《java从入门到精通》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值