2012-10-02 191 views

回答

6

不要做int除法,因为这总是会导致截断的int。相反,你的部门至少使用一个双重值。

double num = 4.0/3.0; 

然后,当你想要显示它作为一个字符串,格式化输出,所以你可以选择你的小数位:

// one way to do it 
// %.3f is for a floating number with 3 digits to the right of the decimal 
// %n is for new line 
System.out.printf(%.3f%n, num); 

Another: 
DecimalFormat decimalFormat = new DecimalFormat("0.000"); 
System.out.println(decimalFormat.format(num)); 
+0

OMG !!!!!!!!!!!!!!!!!!!!谢谢T_T – Jcorretjer

+1

嗯,你只需要有一个是双(如4.0/3或4/3.0),但都不能伤害:) +1 –

+1

@亚历克斯:是的,或'(双)4/3'会工作也很好。 –

0

你也应该使用的String.format(%1.2F,yourDouble)格式化您小数

+3

是的,这段代码将打印双数据,但检查'int/int = int',所以'4/3'将是'1',你应该使用'4.0/3.0'来获得'1.333 ...' –

0

试试这个..

double value= 255.956666; 

BigDecimal bd = new BigDecimal(value).setScale(2, RoundingMode.HALF_UP); 
System.out.println("value="+bd);