将值四舍五入到特定的小数位数很容易:
public static double round(double x, int n){
n = (int)Math.pow(n, 10);
return Math.round(x*n)/n;
}
但是,您能否制定一个算法,根据数字的大小预先假定实际需要四舍五入的小数位数?
我的意思是,如果数字很大(比如100000000.12345
),它不需要那么多的小数精度,所以它可以将它四舍五入到小数点后 1 位或 2 位,
而如果一个数字很小(比如0.00012345
),它需要最大十进制精度
做这样的事情的想法是什么?
编辑: 示例:
argument returned decnum comment
123456789.9 123456789 0 //number is way too large so I don't need any decimal places
12345678.99 12345678 0 //number is still very large.
1234567.899 1234567 0 //still...
123456.7899 123456 0 //...
12345.67899 12345 0 //...
1234.567899 1234 0 //It's pretty large now. Still not small enough to get some decimals.
123.4567899 123.4 1 //Now, number is a little average, so 1 decimal place is included.
12.34567899 12.34 2 //The number is normal, so I want a normal 2 decimal places
1.234567899 1.234 3 //Now it's kinda small, so it now gives 3 decimal places
.1234567899 0.1234 4 //Smaller number, thus greater number of decimal places (4).
.0123456789 0.01234 5 //Even smaller
.0012345678 0.0012345 7 //Larger number of decimal places.
.0001234567 0.0001234567 10 //Smaller and smaller number, greater and greater number of decimals.
我只是在寻找一种方法,当数字接近零时,
我可以增加
小数位数,
并在数字远离零时减少小数位数。