round decimals in javascript - javascript

I use to round decimal in javascript like this:
lat = e.latLng.lat().toFixed(8);
works most of the times but some times I get more decimals as a result.
For example I get 8.341621100000001 from 8.341621100000001 that means that the number is not rounded. Issue is that I need to save it in the db with a 8 decimals precision and that this values are accepted by an API only with a 8 decimals precision.
How can I fix my code to have always it rounded to 8 decimals. We are talking about latitude and longitudes if it can help. Note that I know about issues with working with decimals in javascript but this seems to me like just an issue about using the wrong tool (sometimes it round sometimes it doesn't).
Thanks!

.toFixed() returns a String representing a rounded number, not a Number. As soon as you continue to use the value like a Number again (thanks to JavaScript's lax conversion rules), you re-enter the realm of floating-point inaccuracy.
If the API accepts strings for the numbers, then just call .toFixed(8) where you pass the value to the API.

You can call .toFixed() then send the result through parseFloat():
parseFloat(8.341621100000001.toFixed(8)); // 8.3416211
Or define a helped function to do it for you:
function clip(value, precision) {
return parseFloat(value.toFixed(precision));
};
clip(8.341621100000001, 8); // 8.3416211

Related

toFixed function on large numbers

I have following number with e+ on it
9.074701047887939e+304
I want to take only 9.07
So I tried below , but its not working , its returning full output
console.log(parseFloat(9.074701047887939e+304).toFixed(2));
Ps : I also need the code to work for normal numbers aswell for example 892.0747010 , should output 892.07
toFixed trims digits after the decimal point, but your actual number is very large - it doesn't have a decimal point.
If you don't know in advance whether the number is large or not, one option is to call toFixed(2) on the number first (trimming off and properly rounding digits past the decimal point for small numbers), then using a regular expression to take the numeric part only (removing the e if it exists), then call toFixed(2) again (trimming off and properly rounding digits past the decimal point for large numbers):
const fix = num => Number(
num.toFixed(2).match(/\d+(?:\.\d+)?/)[0]
).toFixed(2);
console.log(fix(9.074701047887939e+304));
console.log(fix(123.4567));
console.log(fix(12345));
Since you mentioned for both 9.074701047887939e+304 and 9.074701047887939, you want the answer to be 9.07.
For 9.074701047887939e-304 I assume you want 9.07 too, although you might actually want 0.00.
const twoDecimal = (a =>
(a.toString().match(/e/) ? Number(a.toString().match(/[^e]*/)[0]) : a).toFixed(2)
);
console.log(twoDecimal(9.074701047887939e+304));
console.log(twoDecimal(9.074701047887939e-304));
console.log(twoDecimal(9.074701047887939));
console.log(twoDecimal(789.074701047887939));
console.log(twoDecimal(0.00001));
console.log(twoDecimal(0.20001));
console.log(twoDecimal(-9.074701047887939e+304));
console.log(twoDecimal(-9.074701047887939e-304));
console.log(twoDecimal(-9.074701047887939));
console.log(twoDecimal(-789.074701047887939));
console.log(twoDecimal(-0.00001));
console.log(twoDecimal(-0.20001));
console.log(twoDecimal(0));

Javascript parse int rounding issue [duplicate]

This question already has answers here:
How to deal with floating point number precision in JavaScript?
(47 answers)
Closed 5 years ago.
If I do the following:
parseInt(parseFloat(9.20)*100*1)/100 // returns 9.19
It returns 9.19 when I want it to return 9.20 what do I need to change to get it to return the correct value?
I have the same issue when I change it to:
parseInt(parseFloat(9.12)*100*1)/100 // returns 9.11
But any other value works fine:
parseInt(parseFloat(9.30)*100*1)/100 // returns 9.30 (correct)
UPDATE:
The solution was this:
(Math.round(9.20*100*1)/100).toFixed(2)
The problem is that 9.20*100 in Javascript returns 919.9999999999999, and not 920, because of floating point errors. When you do a parseInt() on that, it doesn't round to the nearest int, and instead truncates it to 919, which is why your final answer is wrong.
Instead of using parseInt(), a better method to use is Math.round(). This method rounds to the nearest int, turning your 919.99999 into 920, giving you the correct answer.
Because JavaScript uses binary arithmetic, floating point math is an approximation of the base 10 result.
One way to avoid this is to perform integral math, but multiplying your decimals up by a factor large enough to transform them to integers and then divide the answer back down by the same factor.
In this case, I'm not sure why you are using parseInt() or parseFloat() since you are not working with strings in the first place.
Lastly, when you do use parseInt() it is advisable to use the second (optional) argument and supply the radix (the base numeral system to be used to perform the operation) as you can get incorrect values back when the string to be parsed begins with "0" or "0x".
var result = parseInt(9.2*10, 10)/10 // returns 9.19
console.log(result);

Round float to 2 decimals javascript

I have the problem that when i round a number to 2 decimals the parseFloat() function removes .00 from the number. I have tried
var num = parseFloat(Math.round(19 * 100) / 100).toFixed(2);
The return: num="19.00"
The return i need: num = 19.00
I know 19 = 19.00, but i am using a service that always require two decimals .00
The function returns a string with the right value. When i parse it to float the .00 is removed.
You cannot get 19.00 as float, only as string, because numbers always remove trailing zeros.
Maybe you can show us a bit more code to get an idea, there you need these trailing zeros?
Numbers do and can not hold information about their representation. They are only a numerical value.
When you display a number using window.alert, console.log or similar, you are not looking at a number, but at a string. Those display functions convert numbers to strings before displaying them. Number.toFixed also converts numbers into strings, with the difference being that it rounds them to two decimal places, so you end up with another representation of the same number.
What I am trying to say is that to display a number, you cannot get around converting it to a string. Whether you do it explicitly or the display function does it for you. When you send the number to the service that you are using, you are probably also sending a string (JSON, XML, etc. are always strings once you send them). If you need the value of the number for calculations, use it, then convert it in the end. No matter how, you have to do it in the end if you want those 0's at the end.

Large number in javascript

I am working on a calculator in javascript, where user can enter the values in textfield and operation will be performed.
Now if user enters a very large value
for example 5345345345353453453453535
it is converted to 5.345345345353453e+24
I am using parsrInt() to convert it to integers. and it gives me 5.
which is wrong .
Can anybody suggest how to solve it?
Integers in javascript are, like every numbers, stored as IEEE754 double precision floats.
So you can only exactly store integers up to 2^51 (the size of the mantissa).
This means you'll have to design another format for dealing with big integers, or to use an existing library like BigInteger.js (Google will suggest a few other ones).
Taken from Mozilla documentation:
Parses a string argument and returns an integer of the specified radix
or base.
Therefore parseInt() is taking your value as a string 5.345345345353453e+24
It is then ignoring any non-integer values and classing this as a decimal (5.345...) and then evaluating this to 5.
As #dystroy has pointed out, if you wish to carry out calculations with these large numbers you'll need to use a custom format, or use a pre-existing javascript library.
Try parseFloat instead of parseInt.
<script type="text/javascript">
var value = parseFloat(5345345345353453453453535);
alert(value);
</script>

Why does someNum - Math.floor(someNum) give me different decimal numbers

I have some simple javascript which I want to use to determine if a number needs to be rounded.
Example: User enters 1.2346 and the number is rounded to 1.235 and a message should be displayed to the user informing them that the number was rounded.
Rounding the number isn't the issue, but showing the error message to the user is. I need to find the number of digits after the decimal point.
I use the following code to retrieve the decimal places off of a string. I then count the length of the variable to get the decimal places:
var dp = field_value - Math.floor(field_value);
However, When I test this I enter 1.23 for the value of field_value. When I check the value of field value it is indeed 1.23. When I check the value of Math.floor(field_value) it is indeed 1. But then I check the value of dp and it turns out to be 0.22999999999999998
Why does this subtraction not work the way it is expected?
Problem is given by the fact that floating numbers have a finite representation, take a look here and you will understand how and why.
If problem with roundings is just for printing that number you could use something like sprintf for JS that allows you to format float output as you nee.
Trying to do anything too exact and specific with the representation of a floating point number is always going to a tricky situation. As other people have pointed out, this is a property of IEEE-754 floating point standard. Besides treating it as a string and trying to analyze the number, you could also just round it deterministically to the format you want, doing something like:
function roundFloat(num, decimalPlaces) {
multiplier = Math.pow(10, decimalPlaces);
return Math.round(num * multiplier) / multiplier;
}

Categories

Resources