Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何将数字四舍五入到用户给定的小数位数_Java_Math - Fatal编程技术网

Java 如何将数字四舍五入到用户给定的小数位数

Java 如何将数字四舍五入到用户给定的小数位数,java,math,Java,Math,我要做的是获取用户给定的输入操作数,并将当前数字舍入到操作数的小数位数。例如,如果我当前运行的计算器程序中的数字是15.44876,用户输入是2,那么我希望返回的值是15.45,或者至少是15.44 public double round(double operand){ this.answer = Math.round(this.answer, operand); return this.answer; 我知道上面的代码是不正确的,但它只是一个占位符,因为我对此很困惑。你可以

我要做的是获取用户给定的输入操作数,并将当前数字舍入到操作数的小数位数。例如,如果我当前运行的计算器程序中的数字是15.44876,用户输入是2,那么我希望返回的值是15.45,或者至少是15.44

public double round(double operand){
    this.answer = Math.round(this.answer, operand);
    return this.answer;

我知道上面的代码是不正确的,但它只是一个占位符,因为我对此很困惑。

你可以乘以10的适当幂,四舍五入,然后除以10的相同幂。这种方法假设数字在一定范围内,因此溢出不会成为问题

public double round(double value, int places) {
    final double scale = Math.pow(10.0, places);
    return Math.round(value * scale) / scale;
}

如果溢出可能是一个问题,还有其他方法。

这是否回答了您的问题?