View Full Version : adding numbers
kwhubby
12-24-2002, 08:13 AM
usualy when I want to add a number (lets say x and y) I do this x - (-y) that prevents it from being added like a string, that has always been what I used, but in the instance of this
1.1 - (-.1) gives me 2.00000000000001
why???
(try it do this alert(1.1 - (-.1)) )
its not a string why would it add it like a string when its subtracting a negative number??
whats a better way to add numbers without adding strings?
Borgtex
12-24-2002, 11:21 AM
It's a bug: 1.1+0.1=1.2000000000000001 too
kwhubby
12-24-2002, 10:44 PM
what the heck am I supposed to do if I can't add that number?
this is really wierd
Borgtex
12-24-2002, 10:56 PM
Math.floor((1.1+0.1)*1000)/1000
whammy
12-25-2002, 01:06 AM
If you're just trying to prevent a variable being concatenated (as a string) you can use Number(), ParseInt(), or ParseFloat() to change the datatype also.
kwhubby
12-25-2002, 02:32 AM
thanks, I did not know those shortcuts :)
kwhubby
12-25-2002, 02:43 AM
but even this does not work
var a = 1.1
var b = .1
var a = Number(a)
var b = Number(b)
alert(Number(a) - (-Number(b)))
and ParseFloat() gives me an error!
This is a needed error to report to werever bugs for javascript are to be reported to
0.1 is an infinite repeating decimal in binary.
Kind of like 1/3, or 0.33333333333333333... (in base 10).
This has been the glitch behind *many* embarassing failures in costly projects and devices.
RadarBob
12-25-2002, 03:47 AM
It's a bug: 1.1+0.1=1.2000000000000001 too
It's not a bug. It's not a glitch. It's the way computers work. It may come as a suprise but computers are not exact. As jkd pointed out. Another example .. if you were to add 1 + 1/2 + 1/3 + 1/4... + 1/n, and do that forwards then backwards, you'd get different answers. It has to do with how binary numbers, especially fractions, are represented in the computer.
As seen in the other replies there are things we can do to ensure precision as some desired level.
kwhubby
12-25-2002, 05:31 AM
then why does 1.2 + .1 = 1.3 ??
and the Number() thing, and parsefloat() does not help
give me the best way to make it preform normally like a calculator please.
RadarBob
12-30-2002, 01:08 PM
My initial guess is that you should add "5" to the decimal position just beyond your display.
In other words if you are displaying dollars, i.e. two digit: $4.12 for example -> then add 0.005 to your final computation answers to round the result for the last digit in the display. Then truncate all but the two digits you want to display.
chrismiceli
12-30-2002, 08:38 PM
mabey since technically .1 is 0.1, the computer may be reading it as an octal number. if you use parseInt("01") it will read that as an octal number because it starts w/ a 0, try
c = parseInt("1", 10) + parseInt(".1", 10);
alert(c)
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.