开发者

toFixed(3) -6.1e-15 returns -0.000, how can i ditch the minus?

开发者 https://www.devze.com 2023-03-30 12:32 出处:网络
it (\"tests a 开发者_如何学JAVApositive zero\", function() { expect((Math.sin(-1*Math.PI)*300).toFixed(3)).toEqual(\"0.000\");
  it ("tests a 开发者_如何学JAVApositive zero", function() {
     expect((Math.sin(-1*Math.PI)*300).toFixed(3)).toEqual("0.000");
  });

But it fails, because it yields -0.000 (tested on chrome and safari). Removing the - with a regexp.replace is my last (and currently only solution) are there more?


Math.abs(number);//<<absolute value


Wouldn't Math.abs((Math.sin(-1*Math.PI)*300)).toFixed(3) work?

[edit based on comment] or:

Number((Math.sin(-1*Math.PI)*300).toFixed(3)).toFixed(3);


Testing for "positive zero" is incorrect. If you want the number to be 0.000 to three dp, just check that the number is within (-0.0005, 0.0005). e.g.,

expect(Math.sin(-Math.PI) * 300).between(-0.0005, 0.0005);

(You may need to add a between method to your expect, if it doesn't already provide it under a different name.)

0

精彩评论

暂无评论...
验证码 换一张
取 消