从字符串解析浮点值不正确

从字符串解析浮点值不正确

本文介绍了从字符串解析浮点值不正确,双重效果,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 EditText 中输入了 179.9 。当我检索它时,如果将其存储为 float ,则值会有所不同。

I input 179.9 in an EditText. When I retrieve it, the value is different if it's stored as a float.

final EditText valueInput = mEntryDialogView.getValueInput();
final CharSequence input = valueInput.getText();
final String inputAsString = input.toString().trim();
final float asFloat = Float.valueOf(inputAsString); //179.899994
final double asDouble = Double.valueOf(inputAsString); //179.9

这里有些可疑,有人可以向我解释为什么浮动吗值不正确?即使这样,如果我将上述double值转换为float值,也将是错误的。

Something fishy is going on here, could anyone explain to me why the float value is not correct? Even so if I convert the double value above to a float, it will be incorrect.

此外,是否可以做的任何事情以等于实际输入值的方式将其作为浮点数检索?

Moreover, is there anything that can be done to retrieve the value as a float in such a manner that it is equivalent to the actual inputted value?

推荐答案

浮点数 double 不允许精确存储小数,因为浮点数数字以二进制形式(尾数+指数)存储,而不是以十进制数字的形式存储,并且两者之间没有完全匹配的内容。即使系统尝试舍入显示的值以补偿该精度,您也会始终失去一些精度。

float and double don't allow to store decimal numbers exactly, because floating point numbers are stored in a binary form (mantissa + exponent) and not as a list of decimal digits, and there is no exact match between the two. You will always lose some precision, even if the system will try to round the values on display to compensate for that.

浮点数的最大精度大约在6到9个十进制数字之间。

The maximum precision of a Float is approximately between 6 and 9 decimal digits.

如果要存储一个十进制值而不损失精度(例如金额),请使用 BigDecimal String

If you want to store a decimal value without losing precision, for example amounts of money, either use BigDecimal or String.

金额也可以存储为代表美分的整数值,但请确保使用 BigDecimal 或某些 String 操作进行转换而不会损失精度。

Amounts of money can also be stored as an integer value representing cents, but make sure you use a BigDecimal or some String operations to do the conversion without losing precision.

这篇关于从字符串解析浮点值不正确,双重效果,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 21:47