Reputation: 1243
I have several strings which contain numberic values.
I'd like to format these strings so that the numeric values have 1 or 2 decimal places.
Eg. One string might contain the value - "345.98765"
I'd like to format/change this so that there should only be 2 decimal places "345.99".
Can this be done? I am not dealing with any double/float values, these numbers are pulled from XML files.
Thanks
Upvotes: 0
Views: 383
Reputation: 533472
You need to turn the Strings into numbers and then format them.
double d = Double.parseDouble(text);
String formatted = String.format("%.2f", d);
Upvotes: 3
Reputation: 272467
You can use the Formatter
class, or with String.format()
.
Upvotes: 1