← 返回首页
JavaSE系列教程(五十六)
发表时间:2020-02-02 19:20:33
讲解DecimalFormat和BigInteger和BigDecimal.

1.小数的格式化

DecimalFormat类能够解析和格式化任意语言环境中的数,包括对西方语言、阿拉伯语和印度语数字的支持。它还支持不同类型的数,包括整数 (123)、定点数 (123.4)、科学记数法表示的数 (1.23E4)、百分数 (12%) 和金额 ($123)。所有这些内容都可以本地化。

实例:

abstract class Shape{

    protected abstract double getArea();
}

class Circle extends Shape{

    private int r;

    public Circle(int r) {
        this.r = r;
    }

    @Override
    protected double getArea() {
        return Math.PI*r*r;
    }
}

public class Demo {

    public static void main(String[] args) throws Exception {

        double price = 1500000;
        double percent = 0.00789;
        Shape circle = new Circle(10);
        System.out.println("面积是:"+circle.getArea());

        DecimalFormat df = new DecimalFormat("#####.00");//小数点后保留两位
        System.out.println("面积是:"+df.format(circle.getArea()));
        df = new DecimalFormat("0.##E0");//科学计数法
        System.out.println("面积是:"+df.format(circle.getArea()));
        df = new DecimalFormat("###,###,###.00");//千分位表示
        System.out.println("价格是:" + df.format(price));
        df = new DecimalFormat("\u00A4###,###,###.00");//添加货币符号
        System.out.println("价格是:" + df.format(price));
        df = new DecimalFormat("#0.00\u2030");//千分比表示
        System.out.println("比率是:" + df.format(percent));
    }
}

运行结果:
面积是:314.1592653589793
面积是:314.16
面积是:3.14E2
价格是:1,500,000.00
价格是:¥1,500,000.00
比率是:7.89‰

2.BigInteger和BigDecimal

Java中如果我们使用的整数范围超过了long型或者double类型怎么办?这个时候,就只能用软件来模拟一个大整数。java.math.BigInteger/java.math.BigDecimal就是用来表示任意大小的整数/小数。BigInteger内部用一个int[]数组来模拟一个非常大的整数。

BigInteger表示任意大的整数,而BigDecimal表示任意大的小数,且二者用法类似,这里以BigInteger讲解实现两个大整数的加减乘除基本运算。

实例:

        BigInteger num1 = new BigInteger("12345679");
        BigInteger num2 = new BigInteger("97654321");

        BigInteger result = num1.add(num2);//实现加法
        System.out.println(result);
        result = num2.subtract(num1);//实现减法
        System.out.println(result);
        result = num1.multiply(num2);//实现乘法
        System.out.println(result);
        result = result.divide(num1);//实现除法
        System.out.println(result);

运行结果:
110000000
85308642
1205608900028959
97654321