2014-02-12 68 views
0

目前我使用的DecimalFormat类四舍五入双重价值四舍五入双值在Java中

double d = 42.405; 
DecimalFormat f = new DecimalFormat("##.00"); 
System.out.println(f.format(d)); 

output: 42.41; 

我使用硒做浏览器的应用程序测试,所以基于我需要四舍五入值的浏览器。

例如:

IE四舍五入42.405到42.40和其他四舍五入至42.41。但是,如果数值是42.403,42.406,那么我在所有浏览器中看到一致性。所以,现在我已经把一个条件,我的剧本,所以如果浏览器是IE则四舍五入以这样的方式,我应该得到42.40和其他浏览器是应该发生的应该得到42.41。我怎样才能做到这一点?

+0

的【如何把一个数字在Javañ小数]可能重复(http://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-在-JAVA) –

回答

3

您可以为DecimalFormatter指定RoundingMode,但请根据您的需要选择它(我刚刚给出了一个使用HALF_UP的示例)。

double d = 42.405; 
DecimalFormat f = new DecimalFormat("##.00"); 
f.setRoundingMode(RoundingMode.HALF_UP); 
System.out.println(f.format(d)); // Prints 42.41 

另外,您也可以使用BigDecimal(柜面你知道为什么我们平时去BigDecimal而不是double)为同一。

double d = 42.405; 
BigDecimal bd = new BigDecimal(d); 
bd = bd.setScale(2, RoundingMode.HALF_UP); 
System.out.println(bd.doubleValue()); // Prints 42.41 
+0

那么为什么要使用巨大的'BigDecimal'的小号码?为什么不使用正常的格式? –

+0

-1完全不必要的'BigDecimal'。你答案的第二部分看起来不错。 – SebastianH

+0

@SebastianH - 你怎么称呼那不必要的?它可能对你没有用处,或者甚至可能对你有用,但我相信它对未来的用户来说很有用。我给OP上的选项和所有选项都使用了他们需要的选项。我尊重您的投票,但我不会从答案中删除“BigDecimal”部分。 – SudoRahul

1
DecimalFormat f=new DecimalFormat("0.00"); 
String formate = f.format(value); 
double finalValue = (Double)f.parse(formate) ; 
System.out.println(finalValue); 
0

尝试,这可能是有帮助的:

double d = 42.405; 
System.out.println(String.format("%2.2f", d)); 
0

你也能做到 “handly” 为遵循

double d = 42.405; 
final double roundedValue = (Math.round(d * 100)/(double) 100); 

42.405情况下,你会得到42.41和在42.404情况下 - 42.4 所以后

System.out.println(String.format("%2.2f", roundedValue)); 

你会得到所需的输出。 42.4142.40