BigDecimal从Double错误值? [英] BigDecimal from Double incorrect value?

查看:130
本文介绍了BigDecimal从Double错误值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从一个字符串中做一个BigDecimal。不要问我为什么,我只需要它!这是我的代码:

  Double theDouble = new Double(。3); 
System.out.println(The Double:+ theDouble.toString());
BigDecimal theBigDecimal = new BigDecimal(theDouble);
System.out.println(The Big:+ theBigDecimal.toString());

这是我得到的输出?

  The Double:0.3 
The Big:0.299999999999999988897769753748434595763683319091796875

任何想法?

解决方案

当您创建一个double时,值0.3无法正确表示。你可以从一个没有中间值的字符串创建一个BigDecimal,如

  new BigDecimal(0.3)

浮点数表示为二进制分数和指数。因此,有一些数字无法正确表示。在基数10中有类似的问题,数字为1/3,为0.333333333 ..... 1/3的任何十进制数表示不准确。这发生在二进制中的一组不同的分数,0.3是二进制中不精确的集合之一。


I am trying to make a BigDecimal from a string. Don't ask me why, I just need it! This is my code:

Double theDouble = new Double(".3");
System.out.println("The Double: " + theDouble.toString());
BigDecimal theBigDecimal = new BigDecimal(theDouble);
System.out.println("The Big: " + theBigDecimal.toString());

This is the output I get?

The Double: 0.3
The Big: 0.299999999999999988897769753748434595763683319091796875

Any ideas?

解决方案

When you create a double, the value 0.3 cannot be represented exactly. You can create a BigDecimal from a string without the intermediate double, as in

new BigDecimal("0.3")

A floating point number is represented as a binary fraction and an exponent. Therefore there are some number that cannot be represented exactly. There is an analogous problem in base 10 with numbers like 1/3, which is 0.333333333..... Any decimal representation of 1/3 is inexact. This happens to a DIFFERENT set of fractions in binary, and 0.3 is one of the set that is inexact in binary.

这篇关于BigDecimal从Double错误值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆