简体   繁体   English

将字符串转换为Double或从bigdecimal转换为Double而不丢失Java中的任何精度

[英]Converting string to Double or from bigdecimal to Double without losing any precisions in java

I am converting String value to Double or from BigDecimal value to Double using double.value() method in Java. 我正在使用Java中的double.value()方法将String值转换为Double或从BigDecimal值转换为Double But after converting to double, the precision values are truncated. 但是转换为双精度后,精度值将被截断。 Ex. 例如 Str="123.50" or bigDecimalVal="455.780" If I convert these above values to Double using double.valueOf() method , I'm getting the double value as: Str="123.50"bigDecimalVal="455.780"如果我使用double.valueOf()方法将上述值转换​​为Double ,则得到的double值如下:

123.5 or 455.78.

Where '0' is truncated in both the output I've got. 我得到的两个输出中的“ 0”都被截断了。

123.5 and 123.50 both are same mathematically ,If you want proper format value then you can create a holder which will hold both value one for display one for double. 123.5和123.50在数学上都是相同的,如果您想要正确的格式值,则可以创建一个持有人,该持有人将同时持有两个值以显示一个为double的值。

class DoubleDecorator {
    final double val;
    final String string;
    DoubleDecorator(String str) {
        string = str;
        val = Double.parseDouble(str);
    }

   public String getDisplayValue(){
      return string;
   }
   public double getFormattedValue(NumberFormat format){
   //your code
   }
   public double getValue(){
     return val;
   }
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM