这是我的程序。非常简单地说,它应该将输入的数字四舍五入到给定的小数位数。即4.245四舍五入到2位小数会得到4.25。但是,我总是只能将它舍入到一个整数后面...为什么?更令人不解的是,我使用相同的代码在Android和它完美的作品Math.round()无法正常工作
import java.util.Scanner;
public class Rounder {
public static void main(String[] args) {
double input1, roundednumber;
int input2;
Scanner keyboard = new Scanner(System.in);
System.out.println("number to round ");
input1 = keyboard.nextDouble();
System.out.println("decimals");
input2 = keyboard.nextInt();
roundednumber = rounder(input1, input2);
System.out.println(roundednumber);
}
public static double rounder(double number, int decimals){
int multiplier = (int) Math.pow(10, decimals);
double roundednumber;
roundednumber = Math.round(number*multiplier)/multiplier;
return roundednumber;
}
}
这里是从我的android类的片断
double result1 = fv1/(Math.pow(1+(r1/n1),n1*t1));
result1 = (double) (Math.round(result1 * 100))/100;
为了四舍五入,你可以更好地尝试[BigDecimal](http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html).. –
你正在做一个整数除法: Math.round()返回一个int值,然后除以int。写Math.round(...)/(double)相乘;代替。 –
试图做“十进制”舍入像'double's这样几乎保证让你不好的结果。 –