Limit precision of the float number without rounding [duplicate] - javascript

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%;}

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.

JS Preserve decimals ending in zeroes [duplicate]

This question already has answers here:
How can I round a number in JavaScript? .toFixed() returns a string?
(16 answers)
Convert 0 to 0.00 as number
(1 answer)
Is there any way to maintain an integer with .00 in javascript?
(1 answer)
Closed 3 years ago.
In JavaScript, is it possible to "lock" a decimal number, to preserve "floating point" numbers that end with zeroes?
Example, I have 2 different numbers, like this: (pseudo code)
let a = 1.0;
let b = 1.00;
a === b // true, should be false, because different decimals.
print(a) // "1", should be "1.0"
print(b) // "1", should be "1.00"
(should also be different from a "true int" 1)
I want them to identify as different from each other, because they have different amount of zeroes at the end.
But stupidly "efficient" JavaScript rounds them both down to "integer" 1 & therefore they are equal.
I am aware of the Number.toFixed(Number) & Number.toPrecision(Number) functions, but to use them like this I have to first calculate the length of the number, which I can't because JavaScript have already rounded away the zeroes.
I have also been thinking of "cutting" off the number at the decimal point & store them in an array... but again, rounded to an "int" without a decimal point.
(Yes, I know that the concept of "float" doesn't exist in JS, I use it here to diferentiate between numbers with or without decimals).
Thanks for any help.
To compare 2 variables of indefinite type, the variables must be cast internally. This is the problem. Because both A and B are a set with the thickness 1.
Therefore the result is True.
However, if you want to compare the number of zeros, you have to compare them as a string.
So either you declare the variables with
let a = '1.0';
let b = '1.00';
or you cast the variables using
a.toString() === b.toString();

Javascript parsefloat bad subtraction [duplicate]

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

parseInt returning values that differs by 1 [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 7 years ago.
I have data like this:
var currentValue="12345678901234561";
and I'm trying to parse it:
var number = parseInt(currentValue, 10) || 0;
and my result is:
number = 12345678901234560
now lets try:
currentValue="12345678901234567"
in this case parseInt(currentValue,10) will result in 12345678901234568
Can anyone explain me why parseInt is adding/substracting 1 from values provided by me?
Can anyone explain me why parseInt is adding/substracting 1 from values provided by me?
It's not, quite, but JavaScript numbers are IEEE-754 double-precision binary floating point (even when you're using parseInt), which have only about 15 digits of precision. Your number is 17 digits long, so precision suffers, and the lowest-order digits get spongy.
The maximum reliable integer value is 9,007,199,254,740,991, which is available from the property Number.MAX_SAFE_INTEGER on modern JavaScript engines. (Similarly, there's Number.MIN_SAFE_INTEGER, which is -9,007,199,254,740,991.)
Some integer-specific operations, like the bitwise operators ~, &, and |, convert their floating-point number operands to signed 32-bit integers, which gives us a much smaller range: -231 (-2,147,483,648) through 231-1 (2,147,483,647). Others, like <<, >>, and >>>, convert it to an unsigned 32-bit integer, giving us the range 0 through 4,294,967,295. Finally, just to round out our integer discussion, the length of an array is always a number within the unsigned 32-bit integer range.

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.

Categories

Resources