bomortensen
bomortensen

Reputation: 3396

Javascript calculation gives too many zero digits

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:

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

Upvotes: 6

Views: 4669

Answers (5)

KatieK
KatieK

Reputation: 13853

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

Upvotes: 0

Kyle d'Oliveira
Kyle d'Oliveira

Reputation: 6382

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.

Upvotes: 11

webdad3
webdad3

Reputation: 9080

Try this:

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

It is Number Format code for decimal places.

Upvotes: 0

John Fisher
John Fisher

Reputation: 22719

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.

Upvotes: 0

citizen conn
citizen conn

Reputation: 15390

You can do something like this:

value.toFixed(2);

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

Upvotes: 2

Related Questions