开发者

Javascript calculation gives too many zero digits

I think it's t开发者_如何转开发ime get some second opinions on the javascript I'm working on at the moment.

I'm trying to create a calculator to tell people if they can save money by using a subscription etc etc. The calculation itself is done by som inputs from the client and some prevalues from Umbraco CMS.

The result I get from the calculator at the moment is "right" in that the actual numbers are correct, but there's just too many zeroes in it.

The calculator can be found here: my calculator

The test data I'm using is the following:

  • Antal ansatte: 4
  • Gennemsnitlig ordreværdi kr. (ca.): 400
  • Antal ordrer årligt (ca.): 5500
  • Overskudsgrad (hvad er det?): 2.7

Which gives the output: 712800.0000000001

I tried to divide this by 100 and, of course, it just moved the comma/dot two steps the left. Still there's all those zeroes.

Any help/hint is greatly appreciated! :-)

Thanks in advance,

Bo

P.S. The result I'm looking for would be 7128.00


I believe you want to call toFixed on your integer.

(712800.00000001/100).toFixed(2)
"7128.00"

It will change your number into a string, but if it is for display purposes it should be fine.


You can do something like this:

value.toFixed(2);

This will round off all your trailing decimals to only 2.


You may want to use the round() method like this:

var val = Math.round(val*100)/100

This will give you the 2-decimal place precision you want, with rounding when needed.


Try this:

http://www.mredkj.com/javascript/nfbasic2.html

It is Number Format code for decimal places.


I suspect that you're running into floating point rounding errors (Is floating point math broken?). Try the solutions presented in Is there a definitive solution to javascript floating-point errors?.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜