简体   繁体   English

在java中错误的十进制从Double转换为String

[英]Wrong Decimal Converting from Double to String in java

I have A String that is formatted correctly to be cast to a double and it works fine for most decimals. 我有一个格式正确的字符串,可以转换为double,它适用于大多数小数。 The issue is that for .33, .67, and possibly others I haven't tested, the decimal becomes something like .6700000000002 , or .329999999998 . 问题是对于.33,.67,以及可能还有其他我未测试过的,小数点变为.6700000000002.329999999998 I understand why this happens but does any one have a suggestion to fix it. 我理解为什么会发生这种情况但是有人建议修复它。

It's a result of IEEE-754 rounding rules, some numbers cannot be represented precisely in two's complement . 这是IEEE-754舍入规则的结果,有些数字不能用二进制补码精确表示。 For example, 1/10 is not precisely representable. 例如, 1/10不能精确表示。

You can add more precision (but not infinite) by using BigDecimal . 您可以使用BigDecimal添加更多精度(但不是无限)。

BigDecimal oneTenth = new BigDecimal("1").divide(new BigDecimal("10"));
System.out.println(oneTenth);

Which outputs 0.1 哪个输出0.1

使用内部基本2机器表示无法准确表示某些十进制数字。

That's double precision for you. 这对你来说是双精度的。 Binary numbers and decimals don't work well together. 二进制数和小数不能很好地协同工作。 Unless you are doing something really precise it should be fine, if you are printing it you should use either decimal format or printf. 除非你正在做一些非常精确的事情,否则应该没问题,如果要打印它,你应该使用十进制格式或printf。

Value of floating point numbers are not stored directly but with exponential values. 浮点数的值不是直接存储,而是存储指数值。 You may write 3.1233453456356 as number, but this is stored something like 3 and 2^6 in memory. 您可以将3.1233453456356写为数字,但这会在内存中存储类似3和2 ^ 6的内容。 It tries to store a value as close as your number, but those differences can happen. 它会尝试存储与您的数字一样接近的值,但这些差异可能会发生。

It shouldn't be a problem unless you're testing for equality. 除非你正在测试平等,否则它应该不是问题。 With floating-point tests for equality you'll need to allow a "delta" so that: 对于相等的浮点测试,您需要允许“delta”,以便:

if (a == b)

becomes

if (abs(a-b) < 0.000001)

or a similar small delta value. 或类似的小delta值。 For printing, limit it to two decimal places and the formatter will round it for you. 对于打印,将其限制为两位小数,格式化程序将为您舍入。

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

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