Convert a string into a decimal number with 2 decimal places in Java
•
Java
In Java, I try to parse a string of formats "####. ##" into floating point numbers The string should always have 2 decimal places
Even if the value of string is 123.00, the floating-point number should be 123.00 instead of 123.0
This is what I have done so far:
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);
It prints:
string liters of petrol putting in preferences is 010.00 liters of petrol before putting in editor: 10.0
Solution
This is your problem:
litersOfPetrol = Float.parseFloat(df.format(litersOfPetrol));
There you format your float as a string as needed, but then the string is converted to a floating point number again, and then you print your floating point number in stdout to get the standard format Look at this code
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);
By the way, when you want to use decimals, forget the existence of double and float. As others suggest, using only BigDecimal objects will save you a lot of trouble
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
