zoukankan      html  css  js  c++  java
  • Java使用BigDecimal解决浮点型运算丢失精度的问题

    •     @Test
          public void test1(){
              System.out.print(0.05+0.01);
          }

    •     @Test
          public void test2(){
              BigDecimal b1 = new BigDecimal(0.01);
              BigDecimal b2 = new BigDecimal(0.05);
              System.out.print(b1.add(b2));
          }

    •     @Test
          public void test3(){
              BigDecimal b1 = new BigDecimal("0.01");
              BigDecimal b2 = new BigDecimal("0.05");
              System.out.print(b1.add(b2));
          }

    • BigDecimal的加减乘除的工具类
      package com.mmall.util;
      
      import java.math.BigDecimal;
      
      public class BigDecimalUtil {
      
          private BigDecimalUtil(){
      
          }
      
          public static BigDecimal add(double v1,double v2){
              BigDecimal b1 = new BigDecimal(Double.toString(v1));
              BigDecimal b2 = new BigDecimal(Double.toString(v2));
              return b1.add(b2);
          }
      
          public static BigDecimal sub(double v1,double v2){
              BigDecimal b1 = new BigDecimal(Double.toString(v1));
              BigDecimal b2 = new BigDecimal(Double.toString(v2));
              return b1.subtract(b2);
          }
      
          public static BigDecimal mul(double v1,double v2){
              BigDecimal b1 = new BigDecimal(Double.toString(v1));
              BigDecimal b2 = new BigDecimal(Double.toString(v2));
              return b1.multiply(b2);
          }
      
          public static BigDecimal div(double v1,double v2){
              BigDecimal b1 = new BigDecimal(Double.toString(v1));
              BigDecimal b2 = new BigDecimal(Double.toString(v2));
              return b1.divide(b2,2,BigDecimal.ROUND_HALF_UP);//四舍五入,保留两位小数
          }
      }
  • 相关阅读:
    HDOJ 1202 The calculation of GPA
    HDOJ 1197 Specialized Four-Digit Numbers
    HDOJ 1196 Lowest Bit(二进制相关的简单题)
    HDOJ 1194 Beat the Spread!(简单题)
    NOIP2018游记
    CF1043
    洛谷P1280 尼克的任务
    洛谷P1155 双栈排序
    SPOJ6340 ZUMA
    chessboard
  • 原文地址:https://www.cnblogs.com/jimisun/p/8109097.html
Copyright © 2011-2022 走看看