Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java double to string with specific precision

I would like to convert double into String. I want it to have as few digits as possible and maximally 6.

So I found String.format("%.6f", d) which converts my 100.0 into 100.000000. Max precision works correctly, but I would like it to be converted to 100 (minimum precision). Have you got any idea what method is working like that?

like image 392
user3009344 Avatar asked Dec 03 '13 14:12

user3009344


2 Answers

Use DecimalFormat: new DecimalFormat("#.0#####").format(d).

This will produce numbers with 1 to 6 decimal digits.

Since DecimalFormat will use the symbols of the default locale, you might want to provide which symbols to use:

//Format using english symbols, e.g. 100.0 instead of 100,0
new DecimalFormat("#.0#####", DecimalFormatSymbols.getInstance( Locale.ENGLISH )).format(d)

In order to format 100.0 to 100, use the format string #.######.

Note that DecimalFormat will round by default, e.g. if you pass in 0.9999999 you'll get the output 1. If you want to get 0.999999 instead, provide a different rounding mode:

DecimalFormat formatter = new DecimalFormat("#.######", DecimalFormatSymbols.getInstance( Locale.ENGLISH ));
formatter.setRoundingMode( RoundingMode.DOWN );
String s = formatter.format(d);
like image 125
Thomas Avatar answered Oct 05 '22 13:10

Thomas


This is a cheap hack that works (and does not introduce any rounding issues):

String string = String.format("%.6f", d).replaceAll("(\\.\\d+?)0*$", "$1");
like image 23
brettw Avatar answered Oct 05 '22 11:10

brettw