Java程序保存小数
假设值是0.10705921712947473,而您只想保存前3个十进制数字。首先让我们声明值-
double val = 320.0 / 2989.0; BigDecimal big = new BigDecimal(val);
现在,使用setScale()并将参数设置为3以保存3个小数位-
big = big.setScale(3, RoundingMode.HALF_DOWN);
示例
import java.math.BigDecimal; import java.math.RoundingMode; public class Demo { public static void main(String[] args) { double val = 320.0 / 2989.0; BigDecimal big = new BigDecimal(val); System.out.println(String.format("Value = %s", val)); // scale big = big.setScale(3, RoundingMode.HALF_DOWN); double val2 = big.doubleValue(); System.out.println(String.format("Scaled result = %s", val2)); } }
输出结果
Value = 0.10705921712947473 Scaled result = 0.107