6

1.006出力として 1.01 を期待して、小数点以下 2 桁に丸めたい

私がしたとき

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() を使用しても安全ですか?
  • toFixed() クロスブラウザの苦情ですか?

私に提案してください。

PS: スタック オーバーフローで同様の回答を探してみましたが、適切な回答が得られませんでした。

EDIT:

asが 1.051.015を返すのに 1.01 を返すのはなぜですか1.045

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
4

3 に答える 3

4

次のようなものを試してください...

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桁に丸める)

于 2013-02-27T17:43:14.727 に答える