6

I think it's time 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

bomortensen
  • 3,346
  • 10
  • 53
  • 74

5 Answers5

11

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.

Kyle d'Oliveira
  • 6,382
  • 1
  • 27
  • 33
  • That was exactly it went wrong! toFixed() converts the value to a string, so by converting it back with Number(string) worked. Thanks a lot for all of your inputs :) appreciated ! – bomortensen Jun 29 '11 at 17:43
2

You can do something like this:

value.toFixed(2);

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

citizen conn
  • 15,300
  • 3
  • 58
  • 80
0

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.

John Fisher
  • 22,355
  • 2
  • 39
  • 64
0

Try this:

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

It is Number Format code for decimal places.

webdad3
  • 8,893
  • 30
  • 121
  • 223
0

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?.

Community
  • 1
  • 1
KatieK
  • 13,586
  • 17
  • 76
  • 90