gpt4 book ai didi

java - 在Java android中使用Math.round方法四舍五入到小数点后6位

转载 作者:行者123 更新时间:2023-12-01 06:29:31 27 4
gpt4 key购买 nike

我正在使用

double i2 = value * 2.23694;
i2 = (double)(Math.round(i2 * 100)) / 100;

用于四舍五入 double 。但它只四舍五入到小数点后两位。

我希望它是小数点后 6 位。

有没有办法使用Math.round并保留6位小数?

最佳答案

您正在将内容转换为Integer,这会破坏任何舍入。要使用double,请使用小数点(即100.0而不是100)。如果您想要 6 位小数,请使用 1000000.0,如下所示:

 double i2 = value * 2.23694; 
i2 = Math.round(i2*1000000.0)/1000000.0;

但总的来说我认为DecimalFormat是一个更优雅的解决方案(猜测您希望它四舍五入只是为了呈现它):

DecimalFormat f = new DecimalFormat("##.000000");
String formattedValue = f.format(i2);

关于java - 在Java android中使用Math.round方法四舍五入到小数点后6位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22833515/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com