Evan Shen
Evan Shen

Reputation: 1

Format a number stored as a String

I have a String that represents an amount of money passed from input that will optionally contain a decimal point and trailing zeros. It can look like any of these:

inputA = "123.45"
inputB = "123"
inputC = "123.4"
inputD = ".50"

Is there a way to convert these so that they all have the format 0.00 with at least one digit to the left of the decimal point and exactly two to the right without having to convert to a number object like BigDecimal and then back?

Upvotes: 0

Views: 116

Answers (2)

Sunil Rajashekar
Sunil Rajashekar

Reputation: 350

You can use DecimalFormat to achieve formatting.

DecimalFormat format = new DecimalFormat("##0.00");
System.out.println(format.format(10));

Output : 10.00

Upvotes: 1

SilentKnight
SilentKnight

Reputation: 14021

Tricks:

String formattedDouble=String.format("%.2f", Double.valueOf(strDouble));

And, %.2f will format your double as 1.00, 0.20 or 5.21. Double.valueOf(strDouble) convert your String double into a double.

Upvotes: 0

Related Questions