java 在Java中将字符串转换为浮点数而不将其舍入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14037150/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 14:50:42  来源:igfitidea点击:

Converting string to float in Java without round it

java

提问by Kliver Max

Possible Duplicate:
Rounding in java Float.parseFloat

可能的重复:
java Float.parseFloat 中的舍入

I want to convert strings to float i say:

我想将字符串转换为浮点数我说:

System.out.println(Float.parseFloat("1553781.9829"));

Output:

输出:

1553782.0

I say:

我说:

System.out.println(Float.valueOf("1553781.9829"));

Output:

输出:

1553782.0

How to get Float without lossing precision?

如何在不损失精度的情况下获得浮点数?

采纳答案by vishal_aim

use System.out.println(Double.parseDouble("1553781.9829"));instead

使用System.out.println(Double.parseDouble("1553781.9829"));替代

float has a limitation of smaller size (4 bytes) so it's not good for big decimals, double has the double size (8 bytes)

float 具有较小尺寸(4 字节)的限制,因此它不适用于大小数,double 具有双倍尺寸(8 字节)

回答by rai.skumar

If you are looking for accuracy, I would suggest BigDecimal

如果您正在寻找准确性,我会建议BigDecimal

This is just like normal wrapper class which provides methods for all your operations. And yes it takes argument as String as well.

这就像普通的包装类一样,它为您的所有操作提供方法。是的,它也将参数作为字符串。

  BigDecimal bd = new BigDecimal("1553781.9829");
  System.out.println(" bd :"+ bd);  //prints the same value

URL : http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigDecimal.html

网址:http: //docs.oracle.com/javase/1.5.0/docs/api/java/math/BigDecimal.html

回答by Evgeniy Dorofeev

You cannot use float or double without a risk of losing precision. First of all their precision is limited, for float it is approx 7-8 decimal digits, for double ~16 digits. Apart from that Java floating points types are binary internally so they cannot store some decimal fractions without losing precision. If you really need exact decimal fractions use java.math.BigDecimal. Read "Effective Java" Item 48: "Avoid float and double if exact answers are required".

您不能使用 float 或 double 而不会有失去精度的风险。首先,它们的精度是有限的,对于浮点数,它大约是 7-8 位十进制数字,对于双~16 位数字。除此之外,Java 浮点类型在内部是二进制的,因此它们无法在不损失精度的情况下存储一些小数。如果您确实需要精确的十进制分数,请使用 java.math.BigDecimal。阅读“Effective Java”第 48 条:“如果需要确切答案,请避免浮动和双倍”。

回答by Naveenkumar K

Instead of Floatyou can use Double

而不是Float你可以使用Double

System.out.println(Double.valueOf("1553781.9829"));
System.out.println(Double.parseDouble("1553781.9829"));