zoukankan      html  css  js  c++  java
  • BigDecimal类的常用算法

        今天在写代码的时候发现一个不认识的类--BigDecimal,本着无聊的心态加上不认识这个单词,特意去百度了一下,原来这是java.math包中提供的API类BigDecimal,用来对超过16位有效位的数进行精确的运算。

      BigDecimal一共有4个构造方法

      BigDecimal(int) 创建一个具有参数所指定整数值的对象。

      BigDecimal(double) 创建一个具有参数所指定双精度值的对象。

      BigDecimal(long) 创建一个具有参数所指定长整数值的对象。

      BigDecimal(String) 创建一个具有参数所指定以字符串表示的数值的对象。

      BigDecimal 的运算方式 不支持 + - * / 这类的运算 它有自己的运算方法

      BigDecimal add(BigDecimal augend) 加法运算

      BigDecimal subtract(BigDecimal subtrahend) 减法运算

      BigDecimal multiply(BigDecimal multiplicand) 乘法运算

      BigDecimal divide(BigDecimal divisor) 除法运算

      做个小例子:

      

    BigDecimal bigLoanAmount = new BigDecimal("15000.48");   //创建BigDecimal对象
    BigDecimal bigInterestRate = new BigDecimal("0.008");
    BigDecimal bigInterest = bigLoanAmount.multiply(bigInterestRate); //BigDecimal乘法运算
    NumberFormat currency = NumberFormat.getCurrencyInstance();    //建立货币格式化引用
    NumberFormat percent = NumberFormat.getPercentInstance();     //建立百分比格式化用
    percent.setMaximumFractionDigits(3);               //百分比小数点最多3位
    //利用BigDecimal对象作为参数在format()中调用货币和百分比格式化
    System.out.println("Loan amount:	" + currency.format(bigLoanAmount));
    System.out.println("Interest rate:	" + percent.format(bigInterestRate));
    System.out.println("Interest:	" + currency.format(bigInterest));
    

     输出结果:

    Loan amount:    ¥1,111.11
    Interest rate:    0.8%
    Interest:    ¥8.89
  • 相关阅读:
    bag of words in c++
    中位数计算
    awk数据预处理
    收集主机OS相关数据
    Kernel trick----PRML读书笔记
    Error:java: 不再支持源选项 5。请使用 6 或更高版本。
    springboot mybatis日志级别
    java.lang.NoClassDefFoundError: javax/xml/bind/DatatypeConverter
    docker部署Nacos集群
    WARNING: AllowZoneDrifting is enabled. This is considered an insecure configuration option. It will be removed in a future release. Please consider disabling it now.
  • 原文地址:https://www.cnblogs.com/alarm1673/p/4794762.html
Copyright © 2011-2022 走看看