How to make strings from floating-point numbers with '.' (dot) as a decimal separator and not more than 3 digits after floating point?

寵の児 提交于 2019-12-11 10:07:10

问题


I have this code:

public String formatDouble(double d) {
   return String.format("???", d); //Should I use NumberFormat here?
}

For the sample input:

1.00
1,00
1,23
1.234567

I would like to get this output:

1
1
1.23
1.234

How can I configure the pattern (or maybe NumberFormat instance) for producing the correct output?


回答1:


This would do roughly what you need:

Decimalformat df = new DecimalFormat("0.###");
df.setRoundingMode(RoundingMode.FLOOR);
df.format(1.2345);

However, the decimal separator (the dot) will be dependent on current locale. To override it, you may want to provide your own format symbols (see DecimalFormat.setDecimalFormatSymbols()).




回答2:


DecimalFormat should do what you need.




回答3:


Simple way: String.format("%.2f", 1234.23)

If you need thousand separator, add a comma before the dot: String.format("%,.2f", 1234.23) -> the result: 1,234.23.



来源:https://stackoverflow.com/questions/8712504/how-to-make-strings-from-floating-point-numbers-with-dot-as-a-decimal-sepa

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