简体   繁体   English

要转换的字符串

[英]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 and double types are particularly ill-suited for monetary calculations because it is impossible to represent 0.1 (or any other negative power of ten) as a float or double exactly. floatdouble类型特别不适合进行货币计算,因为不可能将0.1(或任何其他10的负幂)表示为floatdouble

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 or long for monetary calculations. 解决此问题的正确方法是使用BigDecimalintlong进行货币计算。

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.

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