[英]String to float conversion
I need to convert a string with value 12.10 to a float value without losing the zero. 我需要将值为12.10的字符串转换为浮点值而不会丢失零。 How can I achieve this in Java.
我怎样才能在Java中实现这一点。
if you aren't worried about memory then 如果你不担心记忆的话
String str = "12.00";
BigDecimal bd= new BigDecimal(str);
System.out.println(bd);//12.00
a) It makes no sense to store trailing zeroes in a float. a)在浮点数中存储尾随零是没有意义的。
b) 12.1 will not map precisely to a floating point value (although this may not be immediately apparent) b)12.1不会精确映射到浮点值(虽然这可能不会立即显现)
From Bloch, J., Effective Java, 2nd ed, Item 48: 来自Bloch,J.,Effective Java,2nd ed,Item 48:
The
float
anddouble
types are particularly ill-suited for monetary calculations because it is impossible to represent 0.1 (or any other negative power of ten) as afloat
ordouble
exactly.float
和double
类型特别不适合进行货币计算,因为不可能将0.1(或任何其他10的负幂)表示为float
或double
。For example, suppose you have $1.03 and you spend 42c.
例如,假设您有1.03美元,而您花费42c。 How much money do you have left?
你还剩多少钱?
System.out.println(1.03 - .42);
prints out
0.6100000000000001
.打印出
0.6100000000000001
。The right way to solve this problem is to use
BigDecimal
,int
orlong
for monetary calculations.解决此问题的正确方法是使用
BigDecimal
,int
或long
进行货币计算。
Example: 例:
BigDecimal price = new BigDecimal("12.10");
Use a java.text.DecimalFormat
: 使用
java.text.DecimalFormat
:
DecimalFormat fmt = new DecimalFormat("0.00");
double floatval = fmt.parse("12.10").doubleValue();
String sval = fmt.format(floatval);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.