Java从入门到精通 第9章 数字处理类

目录

数字格式化

数学运算

随机数

大数字运算


数字格式化

  • 使用DecimalFormat类
    • 使用实例化时设置格式化模式 DecimalFormat(String pattern);
    • 使用applyPattern()方法对数字进行格式化 x = DecimalFormat(); x.applyPattern(String pattern);
    • 使用特殊的方法进行格式化设置setGroupingSize(), setGroupingUse()...

package ex9_DegitalProcessClass;

import java.text.DecimalFormat;

public class ex_9_1_DecimalFormatSimpleDemo {
    //使用实例化对象时设置格式化模式
    static public void SimpleForm(String pattern, double value) {
        DecimalFormat myFormat = new DecimalFormat(pattern);
        //使用特殊方法对数字进行设置
//        myFormat.setGroupingSize(4);  //设置分组大小
//        myFormat.setGroupingUsed(false);  //是否支持分组
        String output = myFormat.format(value);
        System.out.println(value + " " + pattern + " " + output);
    }

    //使用applyPattern()方法对数字进行格式化
    static public void UseApplyPatternMethodFormat(String pattern, double value) {
        DecimalFormat myFormat = new DecimalFormat();
        myFormat.applyPattern(pattern);
        System.out.println(value + " " + pattern + " " + myFormat.format(value));
    }

    static public void main(String[] args) {
        SimpleForm("###,###.###", 123456.789);  //调用静态方法显示
        SimpleForm("00000000.###kg", 123456.789);  //没有数字的地方显示0
        UseApplyPatternMethodFormat("#.###%", 0.789012);  //显示为百分数,百分数保留三位小数
        UseApplyPatternMethodFormat("#.##", 0.789);  //显示小数点后两位
        UseApplyPatternMethodFormat("0.00\u2030", 0.789);  //显示为千分数,小数点后两位,没有数显示0
    }
}

数学运算

  • Math类,主要包括三角函数方法、指数函数方法、取整函数方法、取最大值最小值平均值函数方法,这些函数都被定义为static形式,在程序中应用比较简便,使用Math.数学方法
  • 三角函数方法,sin(),cos(),tan(),asin(),acos(),atan(),toRadians(),toDegrees();
  • 指数函数方法,exp(),log(),log10(),sqrt(),cbrt(),pow(a, b)
  • 取整函数方法,ceil(),floor(),rint()(返回最近的整数,相等返回偶数),round()(+0.5返回最近的整数)
  • 取最大值最小值绝对值函数方法,max(a, b),min(a, b),abs(a)

随机数

  • Math.random()方法,返回一个大于等于0小于1的随机数
    • 使用这个方法可以产生任意范围的随机数、整数、偶数、奇数、字符((char)('a' + Math.random()*('z' - 'a' +1)),加1使其可能取到z)
  • java.util.Random类
    • Random r = new Random();
    • nextInt()返回一个随机整数
    • nextInt(int n) 返回一个大于等于0小于n的整数
    • nextLong() 返回一个随机长整型值
    • netBoolean() 返回一个随机布尔类型值
    • nextFloat() 返回以个随机浮点型值
    • nextDouble 返回一个随机双精度值
    • nextGaussian() 返回一个概率密度为高斯分布的双精度值

大数字运算

  • java.math.BigInteger 支持任意精度的整数,BigInteger类封装了基本的加减乘除,绝对值,相反数,最大公约数,是否为质数
    • public BigDecimal(double val);
    • public BigDecimal(String val); 常用的两个构造方法
    • public BigInteger(String val); 一种构造方法
    • add(), subtract(), multiply(), divide(), remainder(), divideAndRemainder(), pow(), negate(), shiftLeft(), shiftRight(), and(), or(), compareTo(), equals(), min(), max()
  • java.math.BigDecimal 支持任何精度的定点数
    • add(), subtract(), multiply(), divide(BigDecimal idvisor, int scale, int randingMode); 参数为除数,商的小数点后的位数,近似处理模式

发布了46 篇原创文章 · 获赞 0 · 访问量 1030

猜你喜欢

转载自blog.csdn.net/weixin_37680513/article/details/103374328
今日推荐