Java String format decimals only

427 Views Asked by At

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

1

There are 1 best solutions below

1
On

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

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