在 Java 中使用双精度数,是否可以获得纯字符串表示(例如,654987)而不是科学格式(例如,6.54987E5)?
现在我知道我们可以使用该BigDecimal.toPlainString()方法,但是创建一个BigDecimal简单地获取一个String(真的?)对我来说似乎有点草率和低效。有谁知道另一种方式?
double d = 12345678;
System.out.println(d);
System.out.println(String.format("%.0f", d));
1.2345678E7 12345678
请注意,如果您只需要打印此字符串表示形式,您可以简单地使用System.out.printf("%.0f", d).
如果您根本不想要任何舍入,那么我会坚持您的建议,即(new BigDecimal(d)).toPlainString().
使用DecimalFormat/ NumberFormat。
示例中的基本用法:
NumberFormat nf = NumberFormat.getInstance();
output.println(nf.format(myNumber));
对于DecimalFormat,您可以传入格式化模式/区域设置信息以格式化数字。 这个链接是一个很好的使用教程DecimalFormat。
你可以这样做:
double number = 654987;
String plain = String.format("%.0f", number);