格式化浮点数 [英] Formatting Floating Point Numbers
本文介绍了格式化浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类型为 double
的变量,我需要打印精度高达3位小数,但不应该有任何尾随的零...
I have a variable of type double
, I need to print it in upto 3 decimals of precision but it shouldn't have any trailing zeros...
例如。我需要
2.5 // not 2.500
2 // not 2.000
1.375 // exactly till 3 decimals
2.12 // not 2.120
我尝试使用 DecimalFormatter
,我做错了吗?
I tried using DecimalFormatter
, Am i doing it wrong?
DecimalFormat myFormatter = new DecimalFormat("0.000");
myFormatter.setDecimalSeparatorAlwaysShown(false);
谢谢。 :)
推荐答案
尝试模式0。###
而不是0.000
:
import java.text.DecimalFormat;
public class Main {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("0.###");
double[] tests = {2.50, 2.0, 1.3751212, 2.1200};
for(double d : tests) {
System.out.println(df.format(d));
}
}
}
输出:
2.5
2
1.375
2.12
这篇关于格式化浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文