Java Math.pow() Rounding Error

后端 未结 4 1782
囚心锁ツ
囚心锁ツ 2021-01-25 14:24

I\'m having trouble with (what I suspect is) a rounding error.

I have a string, 0.686357E-01, which I\'m trying to convert to a double. I\'ve been able to s

相关标签:
4条回答
  • 2021-01-25 14:34

    0.0686357 is not exactly representable as a double-precision value.

    Two solutions:

    • Use e.g. BigDecimal.
    • Limit the displayed precision to a certain number of significant figures when converting back to human-readable.
    0 讨论(0)
  • 2021-01-25 14:38

    Floating point numbers do not have perfect precision. If that is an issue, use BigDecimal:

    String string = "0.686357E-01";
    BigDecimal number = new BigDecimal(string);
    System.out.println(number);
    
    0 讨论(0)
  • 2021-01-25 14:47

    Double will print always like that, but the value will remain correct. You'll need to format the output to get the correct value. See DecimalFormat class.

    0 讨论(0)
  • 2021-01-25 14:48

    You don't need to split it, Double.parseDouble can handle those kinds of numbers just fine.

    double number = Double.parseDouble("0.686357E-01");
    

    See? It works!

    0 讨论(0)
提交回复
热议问题