0

我有一个双重价值 - double d = 1.67303521E8; 无论我用来格式化它,我都无法获得实际的解决方案。

我试过了:

DecimalFormat df = new DecimalFormat("#.000");

public static double round(double value, int places) {
    if (places < 0) throw new IllegalArgumentException();

    long factor = (long) Math.pow(10, places);
    value = value * factor;
    long tmp = Math.round(value);
    return (double) tmp / factor;
}

但始终输出为 1.67303521E8。S0 最后我用了

str.substring( 0,5 )

我想知道解决这个问题的实际解决方案是什么

4

2 回答 2

1

这样,它应该按照您想要的方式进行格式化:

//This is just an object that can format numeric values into strings...
DecimalFormat df = new DecimalFormat("#.000");

//computation
long factor = (long) Math.pow(10, places);
value = value * factor;
long tmp = Math.round(value);
double result = (double) tmp / factor;

//formatting to string of specified format
String formattedValue = df.format(result);

//optional...
System.out.println(formattedValue);

你的错误可能是——这是一个常见的错误——你认为通过做某事,你可以神奇地改变双精度值在内存中的存储格式。这不是真的。双打、日期等始终存储在本地结构中,您必须将它们格式化为以适当的指定格式呈现给人类。

但是,您在 substring() 方法中犯了一个重大错误:格式E- 也称为科学记数法 - 在 E 之后指定一个指数,它指定该值必须乘以 10 的哪个指数......这个重要信息丢失了在您的实施中...

1.67303521E8

实际上是

167303521

并不是

1.673
于 2013-10-03T16:26:49.593 回答
1

再试一次

System.out.println(new DecimalFormat("#.000").format(1.67303521E8));

输出

167303521.000

于 2013-10-03T16:31:55.703 回答