Sud*_*han 6 javascript math rounding
我想要舍入1.006到两位小数,期望输出为1.01
当我做的时候
var num = 1.006;
alert(Math.round(num,2)); //Outputs 1
alert(num.toFixed(2)); //Output 1.01
Run Code Online (Sandbox Code Playgroud)
同样的,
var num =1.106;
alert(Math.round(num,2)); //Outputs 1
alert(num.toFixed(2));; //Outputs 1.11
Run Code Online (Sandbox Code Playgroud)
所以
请建议我.
PS:我尝试搜索堆栈溢出类似的答案,但无法得到正确的答案.
EDIT:
为什么1.015返回1.01,其中1.045返回1.05
var num =1.015;
alert(num.toFixed(2)); //Outputs 1.01
alert(Math.round(num*100)/100); //Outputs 1.01
Run Code Online (Sandbox Code Playgroud)
在哪里
var num = 1.045;
alert(num.toFixed(2)); //Outputs 1.04
alert(Math.round(num*100)/100); //Outputs 1.05
Run Code Online (Sandbox Code Playgroud)
试试像......
Math.round(num*100)/100
1) Multiple the original number by 10^x (10 to the power of x)
2) Apply Math.round() to the result
3) Divide result by 10^x
Run Code Online (Sandbox Code Playgroud)
来自:http://www.javascriptkit.com/javatutors/round.shtml
(将任意数字舍入到x小数点)
| 归档时间: |
|
| 查看次数: |
3227 次 |
| 最近记录: |