2013-10-03 48 views
0

我有一个双值 - double d = 1.67303521E8; 无论我用什么格式,我无法得到实际的解决方案。如何舍入/格式十进制后的数字,如果十进制值包含E作为一项

我想:

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) 

我想知道什么是真正的解决方案来解决这个问题

+0

什么是您预期的输出? –

回答

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); 

你的错可以 - 这是常见的 - 是你假设通过做某事,你可以奇迹般地改变格式的双值是在内存中存储。这不是真的。双打,日期等始终存储在本地结构中,您必须格式它们可以以适当的指定格式呈现给人类。

但是,你有一个炽热错误的串()的方法:E格式 - 也被称为是科学记数法 - 的E,指定哪个值10指数后,必须指定一个指数通过......这重要信息丢失在您的实现乘...

1.67303521E8 

实际上是

167303521 

而且不

1.673 
1

再试

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

输出

167303521.000

+0

我没有看到这与我的回答有何不同。 – ppeterka