2013-02-27 113 views
2

我要舍1.006到兩位小數預期1.01作爲輸出Math.round舍入誤差

當我做

var num = 1.006; 
alert(Math.round(num,2)); //Outputs 1 
alert(num.toFixed(2)); //Output 1.01 

同樣,

var num =1.106; 
alert(Math.round(num,2)); //Outputs 1 
alert(num.toFixed(2));; //Outputs 1.11 

因此

  • 每次都使用toFixed()是否安全?
  • 是要修復()跨瀏覽器投訴嗎?

請給我建議。

P.S:我試着尋找類似的答案堆棧溢出,但無法得到正確的答案。

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 

凡爲

var num = 1.045; 
alert(num.toFixed(2)); //Outputs 1.04 
alert(Math.round(num*100)/100); //Outputs 1.05 
+0

'Math.round'四捨五入到最接近的整數。 – Jrod 2013-02-27 17:45:33

+0

@Jrod:如果你參考[這個小提琴](http://jsfiddle.net/_Sud/qmRyU/)它也輸出十進制值 – Sudarshan 2013-02-27 17:47:06

+0

@nlsbshtr:感謝指出它,你能檢查我的編輯,並幫助我的第二個問題 – Sudarshan 2013-02-27 17:56:30

回答

3

嘗試這樣從mething像...

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 

http://www.javascriptkit.com/javatutors/round.shtml

(四捨五入任何數量爲x小數點)

+0

感謝您的回答,順便說一句,你是如何達到100的? – Sudarshan 2013-02-27 17:45:19

+0

@Sudarshan 10^x給你x個小數點,10^2 = 100 = 2個小數點。 – jbabey 2013-02-27 17:48:45

+0

@jbabey:謝謝你的回答,你能檢查我的編輯,你能解釋一下什麼是四捨五入的正確方法 – Sudarshan 2013-02-27 17:57:06