mmmbaileys
mmmbaileys

Reputation: 1243

Format a string which contains numbers

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

Answers (3)

Peter Lawrey
Peter Lawrey

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

Jigar Joshi
Jigar Joshi

Reputation: 240860

More precisely you could use DecimalFormat

Upvotes: 1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

You can use the Formatter class, or with String.format().

Upvotes: 1

Related Questions