Java double to string with specific precision

↘锁芯ラ 提交于 2019-12-05 01:01:01
Thomas

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);
brettw

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

String string = String.format("%.6f", d).replaceAll("(\\.\\d+?)0*$", "$1");

String.format("%.0", d) will give you no decimal places

-or-

String.format("%d", (int)Math.round(f))

Couldn't you just make a setPrecision function, sort of like this

private static String setPrecision(double amt, int precision){
   return String.format("%." + precision + "f", amt);
}

then of course to call it

setPrecision(variable, 2); //

Obviously you can tweek it up for rounding or whatever it is you need to do.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!