在Java中将字符串转换为带有2个小数位的十进制数

adi*_*yag 5 java string floating-point number-formatting

在Java中,我试图将一串格式解析"###.##"为float.该字符串应始终具有2个小数位.

即使字符串中有值123.00,浮子也应该是123.00,不123.0.

这是我到目前为止:

System.out.println("string liters of petrol putting in preferences is " + stringLitersOfPetrol);

Float litersOfPetrol = Float.parseFloat(stringLitersOfPetrol);

DecimalFormat df = new DecimalFormat("0.00");
df.setMaximumFractionDigits(2);

litersOfPetrol = Float.parseFloat(df.format(litersOfPetrol));

System.out.println("liters of petrol before putting in editor: " + litersOfPetrol);
Run Code Online (Sandbox Code Playgroud)

它打印:

string liters of petrol putting in preferences is 010.00 
liters of petrol before putting in editor: 10.0
Run Code Online (Sandbox Code Playgroud)

Eri*_*ski 12

Java将String转换为十进制:

String dennis = "0.00000008880000";
double f = Double.parseDouble(dennis);
System.out.println(f);
System.out.println(String.format("%.7f", f));
System.out.println(String.format("%.9f", new BigDecimal(f)));
System.out.println(String.format("%.35f", new BigDecimal(f)));
System.out.println(String.format("%.2f", new BigDecimal(f)));
Run Code Online (Sandbox Code Playgroud)

这打印:

8.88E-8
0.0000001
0.000000089
0.00000008880000000000000106383001366
0.00
Run Code Online (Sandbox Code Playgroud)


Dav*_*ann 9

这行是你的问题:

litersOfPetrol = Float.parseFloat(df.format(litersOfPetrol));
Run Code Online (Sandbox Code Playgroud)

在那里你根据需要将你的浮动格式化为字符串,但是然后该字符串再次转换为浮点数,然后你在stdout中打印的是你的浮点数得到了标准格式.看看这段代码

import java.text.DecimalFormat;

String stringLitersOfPetrol = "123.00";
System.out.println("string liters of petrol putting in preferences is "+stringLitersOfPetrol);
Float litersOfPetrol=Float.parseFloat(stringLitersOfPetrol);
DecimalFormat df = new DecimalFormat("0.00");
df.setMaximumFractionDigits(2);
stringLitersOfPetrol = df.format(litersOfPetrol);
System.out.println("liters of petrol before putting in editor : "+stringLitersOfPetrol);
Run Code Online (Sandbox Code Playgroud)

顺便说一句,当你想使用小数时,忘记存在double和float,就像其他人建议的那样,只使用BigDecimal对象,它会为你省去很多麻烦.


fge*_*fge 5

用途BigDecimal:

new BigDecimal(theInputString);
Run Code Online (Sandbox Code Playgroud)

它保留所有小数位.并且您确定精确的表示,因为它使用十进制基数而不是二进制基数来存储精度/比例/等.

它是不受般精准的损失float或者double是,除非你明确地要求它.