简体   繁体   English

如何写具有三位有效数字的字符串而不四舍五入

[英]How to write string with 3 significant digits without rounding

I would like the convert string value with 3 significant digits. 我想要3位有效数字的转换字符串值。

I am using this code : 我正在使用此代码:

String s = "0,92";
float f = Float.parseFloat(s);
DecimalFormat formatter = new DecimalFormat("#,###");
String end = formatter.format(f);

The result is end= 0.000. 结果是end = 0.000。 But ı want to get end = 0,920. 但是我想结束= 0,920。 How can i do that? 我怎样才能做到这一点?

This works for me: 这对我有用:

String s = "0.92";
float f = Float.parseFloat(s);
DecimalFormat formatter = new DecimalFormat("0.000");
String end = formatter.format(f);
System.out.println(end); 

Please note the '.' 请注意“。” in the String s and the pattern in DecimalFormat. 在String中,并在DecimalFormat中使用模式。
',' here means the 1000 marker, ie. “,”在这里表示1000标记,即。 1,000,000.00 for one million. 1,000,000.00为一百万。

If in your current locale the decimal separator is a dot then you will get 0.920. 如果在您当前的语言环境中,小数点分隔符是一个点,那么您将得到0.920。 If you want to get the result independent from you current locale to have as decimal separator a comma and as thousand separator a dot you could achieve it for example like this 如果要获得独立于当前语言环境的结果,以逗号作为小数点分隔符,以小数点作为千位分隔符,则可以这样实现

String s = "0.92";
float f = Float.parseFloat(s);
DecimalFormat formatter = new DecimalFormat("0.000", DecimalFormatSymbols.getInstance(Locale.GERMANY));
String end = formatter.format(f);
System.out.println("end = " + end);

This prints 此打印

 end = 0,920

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM