水题是水不过我学到了一点,怎么求有效数
1.求概数的整数部分位数
2.得出剩下的有效数位数power
3.该数向后移power位,四舍五入之后向前移power位
例如:1.5335求3位有效数
整数部分为1
1.535*100=153.5
153.5四舍五入 154
154/100=1.54
public static double roundToSignificantFigures(double num, int n) {
if(num == 0) {
return 0;
}
final double d = Math.ceil(Math.log10(num < 0 ? -num: num));
final int power = n - (int) d;//求出小数部分的位数
final double magnitude = Math.pow(10, power);//得出我们的模
final long shifted = Math.round(num*magnitude);//四舍五入
return shifted/magnitude;//还原
}