2012-08-22 25 views
1

我正在通过类十进制格式,因为我试图在Java中格式化一个十进制数到2个小数位或3个小数位。关于舍入一个值到某个小数点

我想出了如下所示的解决方案,但也请让我知道有没有其他的选择,Java提供我们实现相同的事情..!

import java.text.DecimalFormat; 

public class DecimalFormatExample { 

    public static void main(String args[]) { 

     //formatting numbers upto 2 decimal places in Java 
     DecimalFormat df = new DecimalFormat("#,###,##0.00"); 
     System.out.println(df.format(364565.14)); 
     System.out.println(df.format(364565.1454)); 

     //formatting numbers upto 3 decimal places in Java 
     df = new DecimalFormat("#,###,##0.000"); 
     System.out.println(df.format(364565.14)); 
     System.out.println(df.format(364565.1454)); 
    } 

} 

Output: 
364,565.14 
364,565.15 
364,565.140 
364,565.145 

请指教有什么其他替代品,Java提供我们实现相同的事情.. !!

+3

有什么关于这个解决方案,你不满意吗? – Hbcdev

+0

我不知道我明白你的问题与上面的代码是... – posdef

+1

E.g.这个问题包含几个方法来做舍入/截断/格式的双打:http://stackoverflow.com/q/2808535/56285 但是,如果DecimalFormat做你所需要的,为什么不使用它呢? – Jonik

回答

1

如果您对重新定义DecimalFormat感到困扰,或者您怀疑需要重新定义多次,则还可以使用String.format()进行内联格式化。检查syntax for Formatter,尤其是数字子标题。

0

这里是四舍五入替代...

double a = 123.564; 
double roundOff = Math.round(a * 10.0)/10.0; 
System.out.println(roundOff); 
roundOff = Math.round(a * 100.0)/100.0; 
System.out.println(roundOff); 

输出是

123.6 
123.56 

0数方而乘除决定四舍五入。

0

这是一种方法。

float round(float value, int roundUpTo){ 
    float x=(float) Math.pow(10,roundUpTo); 
    value = value*x; // here you will guard your decimal points from loosing 
    value = Math.round(value) ; //this returns nearest int value 
    return (float) value/p; 
}