Javascript parsefloat bad subtraction [duplicate] - javascript

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 6 years ago.
I am going to subtract two floats but I get 999998.7799999999 why ? It real result is 999998.78
Money1="2,000,001.44 $";
Money2="1,000,002.66 $"
Money1= Number(Money1.replace(/[^0-9\.]+/g,""));
Money2= Number(Money2.replace(/[^0-9\.]+/g,""));
console.log(parseFloat(Money1)-parseFloat(Money2));

You can use toFixed(2) because you are working only with two digits:
toFixed() returns a string representation of numObj that does not use exponential notation and has exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. If numObj is greater than 1e+21, this method simply calls Number.prototype.toString() and returns a string in exponential notation.
The snippet:
Money1="2,000,001.44 $";
Money2="1,000,002.66 $"
Money1= Number(Money1.replace(/[^0-9\.]+/g,""));
Money2= Number(Money2.replace(/[^0-9\.]+/g,""));
result = (Money1 - Money2).toFixed(2);
console.log(result);

Your Problem is related to floating point precision.
You can find a explanation here.

The result you want is just a rounded version of the what Javascript is producing (read more about floating point operations in Javascript). You can round the result yourself to get the formatting you desire:
Money1="2,000,001.44 $";
Money2="1,000,002.66 $"
Money1= Number(Money1.replace(/[^0-9\.]+/g,""));
Money2= Number(Money2.replace(/[^0-9\.]+/g,""));
Rounded = Math.round((parseFloat(Money1)-parseFloat(Money2)) * 100) / 100;
console.log(Rounded);

The result is due to floating point precision, the Python docs have a great explanation. https://docs.python.org/2/tutorial/floatingpoint.html

Related

String Convertion To Integer In JS Problem [duplicate]

This question already has answers here:
What is JavaScript's highest integer value that a number can go to without losing precision?
(21 answers)
Closed 4 days ago.
I was expecting 6145390195186705543 but gave me 6145390195186705000.
This is my code:
var str = '6145390195186705543';
var num = parseInt(str);
console.log(num)
JavaScript uses 64-bit floating point numbers, which can represent numbers in the range -(2^53 - 1) to (2^53 - 1). In this case, the number 6145390195186705543 is out of this range and cannot be accurately represented in JavaScript. When trying to convert the string "6145390195186705543" to a number using the parseInt() function, JavaScript cannot represent the number exactly and rounds it to the nearest floating point number, resulting in 6145390195186705000.
To work with such large numbers, you can use special libraries for working with large arithmetic, such as BigInt or BigNumber.

Limit precision of the float number without rounding [duplicate]

This question already has answers here:
Truncate number to two decimal places without rounding
(43 answers)
Closed 2 years ago.
is there a way to have 2 numbers after comma without rounding the value. I want the exact value. Math.round() and toFixed() give the value rounded.
You can do the workaround with help of Math.ceil() and Math.floor() functions.
Another way, is treat is as an string and use .slice()
i.e:
number = number.slice(0, number.indexOf(".")+3); //this should give you 2 decimals
Number(number); //Convert it to "Number" again, so you can operate with it
Solution without type conversions
While solving the issue, you should bear in mind that bouncing back and forth between data types may cost you some of app performance wasted
Instead, I'd suggest to modify input number directly:
shift the dot n positions to the right by multiplying your number by 10 in power of n (10**n)
cut off what's left after dot, using bitwise OR (|) that implicitly turns the float into integer
divide the result by 10 in power of n to shift the dot n positions back to the left
Following is a quick live-demo:
const num = 3.14159265,
precision = 4,
limitPrecision = (n,p) => (0|n*10**p)/10**p
console.log(limitPrecision(num, precision))
.as-console-wrapper{min-height:100%;}

Why JavaScript return me a wrong result in this subtraction of decimals values? [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 7 years ago.
I am pretty new in JavaScript and I have found a very strange situation doing an extremely simple mathematical operation: a subtraction.
So in a jQuery function I have this code:
saldoRicalcolato = finanziamento - variazioneAnticipoNumber;
Where finanziamento and variazioneAnticipoNumber are 2 numbers having decimal digits.
It works almost always good except for some specific values.
You can replicate the strange behavior performing this statement into the FireBug console:
2205.88 - 1103.01
1102.8700000000001
So in this case the result is substantially wrong because I obtain 1102.8700000000001 and not 1102.87 as I expected.
Why? What am I missing? Is it a JavaScript engine bug or something like this? Possible?
It's not a JavaScript problem but a more general computer problem. Floating number can't store all decimal numbers properly, because they store stuff in binary For example:
0.5 is store as b0.1
but 0.1 = 1/10 so it's 1/16 + (1/10-1/16) = 1/16 + 0.0375
0.0375 = 1/32 + (0.0375-1/32) = 1/32 + 00625 ... etc
so in binary 0.1 is 0.00011...
but that's endless. Except the computer has to stop at some point. So if in our example we stop at 0.00011 we have 0.09375 instead of 0.1.
It doesn't depend on which language but on the computer, what depends on the language is how you display the numbers. Usually the language will round numbers to an acceptable representation but apparently JavaScript doesn't.
If you're looking to get 1102.87. You'll need to set the decimal place to 2 by using toFixed()
This is just a solution of getting the number you want.
alert((2205.88 - 1103.01).toFixed(2));

Problems with parseInt method [duplicate]

This question already has answers here:
parseInt rounds incorrectly
(2 answers)
Closed 7 years ago.
The parseInt function made my number loose precision: the last two digits changed from 18 to 20:
console.log(parseInt('76561198236425518', 10));
76561198236425520
Why did that happen and how to fix it?
Numbers are stored as floating point with a 53-bit manttissa. This limits the precision you can have to less than what you have in that number of yours, hence it has to round to the nearest floating point number it can represent.
The actual number of bits needed to represent a number N can be calculated as about log2N or, if you're working on a calculator that can't calculate logarithms to base two, logxN/logx2.
The value of log276561198236425518, roughly 56.1, shows that it requires about 56 bits, which is why it's not exact near the end.

Javascript rounding issue [duplicate]

This question already has answers here:
Why does floating-point arithmetic not give exact results when adding decimal fractions?
(31 answers)
Closed 11 months ago.
I've got a weird maths/rounding problem in Javascript.
The snippet below is a very basic example of the code I'm running. Obviously it's not this exact code, but I'm taking a decimal value from a text box, working out a percentage and taking this away from one.
var ten = "10";
var eight = "8";
alert(1 - (eight/ten));
The problem is the answer is 0.2 but the calculation returns 0.1999999999999996. Yet if I do 1 + (eight/ten) 1.8 is returned. What is going on?
Welcome to the world of floating-point numbers!
Computers don't actually work with decimal numbers--i.e. numbers in base ten, the way we use them in normal life. They work with binary numbers, and that includes floating-point numbers. They're represented in binary as well, and that means that "number of decimal places" is not always a meaningful property of a floating-point number.
For instance, a floating-point number cannot exactly represent 0.1, and you'll get something like 0.1000000001 if you try to use it in your code. The exact value you get varies by implementation, and is not correctable by subtracting the difference, as the computer can't tell that there is a difference--that's as close as it can get to 0.1.
(Stole most of this answer from a previous answer of mine.)
It's because of the way floating point numbers are represented.
I have the same result on my android device which means your device or computer works with 64 bits floating point representation. For correct result, you must limit displaying your result to 15 digits. I found this workaround : running :
var res = 1 - 0.8;
var roundedRes = parseFloat(res.toPrecision(15) ) ;
alert ("res="+res+"\n" + "roundedRes="+roundedRes);
ouputs :
res=0.19999999999999996
roundedRes=0.2
JavaScript use binary floating point for representation of numbers like 1/2,1/8...1/1024. But decimal fractions which we mostly use are represented in form 1/10,1/100...
This will not be a problem with JavaScript only but with all languages that use binary floating point representation.

Categories

Resources