darksaga
darksaga

Reputation: 2186

Java String format decimals only

Is there a way to format a double using String.format() to only get the decimals?

System.out.println(String.format("%.2f", 1.23456d));

As expected, the above line returns '1.23', but in this case I'm only interested in '.23'. Aditionally I'm not interested in anything before the decimal sign, also no leading 0.

Is this possible with String.format() or do I need to use DecimalFormat?

Cheers

Upvotes: 1

Views: 424

Answers (1)

blackSmith
blackSmith

Reputation: 3154

You can post-process the output of String.format :

String.format("%.2f", 1.23456d).replaceFirst("^[^.//]+", "")

Upvotes: 1

Related Questions