round numbers in js - javascript

I would like to round 45.19202405202648 to 3 decimal places.
I tried :
n.toFixed(3);
also https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
Math.round10(n, -3);
myNamespace.round(n, 3);
and
Math.round(n * 1000 + Number.EPSILON ) / 1000;
but these solutions returns 45.19199999999999 insted of 45.192
EDIT : Real question is if I do 65.19202405202648.toFixed(3) - 20 I get 45.19199999999999
Thanks for your help

Your Arithmetical coprocessor is buggy. Try a different computer.

x - number to be rounded; n - number of decimals;
function roundPlus(x, n) {
if (isNaN(x) || isNaN(n)) return false;
var m = Math.pow(10, n);
return Math.round(x * m) / m;
};

Try this:
let num = 45.19202405202648;
console.log(num.toFixed(3));

So it sounds like you've got 2 things going on here. First is the rounding part, which appears to be working as expected. The second issue is just that floating point numbers don't always map well to nice easy to read strings. So, to convert it to a nice string, you can use:
var roundedNum = Math.round(num * 1000) / 1000;
var displayString = roundedNum.toFixed(3)
You need to both round and use .toFixed to get the expected result.

There is a function in javascript called toFixed(). This will return a number with a fixed amount of decimal places. This WILL round 90% of the time but sometimes it does not round perfectly. There is no way to round perfectly without external libraries. For example you would do this:
n.toFixed(3);
I see you have tried this already, it should work. Try and run it again or in a controlled environment.

Related

toFixed not working for value 3.675

I am facing the issue while round numbers in 2 decimal points using javascript function toFixed
It's working for all the values except some cases
For example :
Value is : 3.675 Then it should be 3.68
I have tried it as below
var ans = Number(DiscountValue).toFixed(2);
I have even tried with the following code
var ans = parseFloat(DiscountValue).toFixed(2);
But its returning 3.67
Anyone face this issue before
Plz guide how we can sort this !
Math.round(num * 100) / 100
It will give you the result you are expecting

Round to 2 decimal places with JS

Alright so this is in a JS file that is called by an html page. Overall t_price changes to many different prices in USD dollars.
T_price then gets converted into Singapore dollars. Doing this makes numbers like 499 into 510.38294. I need to round any number into just 2 decimal places. This is my code:
r_price=t_price*1.27;
m_price=Math.round(r_price*100/100);
document.getElementById("v_price").value="$"+m_price;
For what ever reasons - this is rounding to no decimal places instead of 2. So 510.38294 becomes just 510 instead of 510.38.
Am I using the wrong math.round? Any help would be great.
You wrote :
m_price=Math.round(r_price*100/100);
You meant :
m_price=Math.round(r_price*100)/100;
Math.round() is doing exactly what you asked it to - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round.
What you want to use for is toFixed() like so
m_price = m_price.toFixed(2);
X - the number; N - number of decimals
function roundPlus(x, n) {
if (isNaN(x) || isNaN(n)) return false;
var m = Math.pow(10, n);
return Math.round(x * m) / m;
};

toFixed(2) function not working

This one is weird, because I got it running in this fiddle but it is not working in the main fiddle. I believe the code is the same.
Here is the main function:
window.setInterval(function(){
for(var i=0; i < companies.length; i++) {
var randomVal = (Math.random()*(10 - (-10) + 1)) + (-10);
randomVal = randomVal / 100;
randomVal = Number(randomVal.toFixed(2));
companies[i].price += randomVal;
//companies[i].price = companies[i].price.toFixed(2);
$('#price'+i).html(companies[i].price);
}
}, 1000);
A value like 34.569999999999986 isnt been cut down to 34.56.
Any idea what is wrong?
This has to do with a common problem that occurs when converting between binary floating point values and decimal representations. See this fiddle, which is like your "working" one, but I altered the price value so that it also breaks.
Here's an even simpler demo that gets right to the heart of the problem: http://jsfiddle.net/2NHSM/4/
As you can see, the output of 1.23 - 1 is 0.22999999999999998. That's obviously off by a little bit, but it has to do with the way computers represent numbers.
Computers hold numbers as binary digits. 1.23 is actually a "repeating decimal" in binary (just like 1/7 is repeating in decimal), so there's no 100% accurate way to store it. As a result, when you subtract 1.23 - 1 you get an answer that is slightly off because 1.23 was never accurate to begin with.
The same thing is happening in your case. To fix it, just use toFixed right before you display the value, not before you add something else to it.
Update
Here's a working fiddle: http://jsfiddle.net/2NHSM/6/
Update 2
Also note that toFixed can have unexpected rounding behavior. Try the following in the console:
1.35.toFixed(1);
// => 1.4
1.45.toFixed(1);
// => 1.4
You might want to use Math.round instead.
Math.round(1.35 * 10) / 10
// => 1.4
Math.round(1.45 * 10) / 10
// => 1.5
Floating points are approximations so when you add, they don't always end up clean numbers. Just call toFixed when you display it:
companies[i].price += randomVal;
$('#price'+i).html(companies[i].price.toFixed(2));
Demo
This is why your //companies[i].price = companies[i].price.toFixed(2); didn't work:
toFixed() returns a string, so after the first call, companies[i].price is a string. When you do companies[i].price += randomVal;, it is doing string concatenation instead of numeric addition. It'll produce something like:
577.05
577.050.05
577.050.050.1
So you can't call toFixed on it anymore because:
It's a string
It's not even a valid number
So, how would you fix that? Convert it to a number by multiplying by 1 (or Number());
companies[i].price += randomVal;
companies[i].price = companies[i].price.toFixed(2)*1;
$('#price'+i).html(companies[i].price);
Demo
With either of these solutions, the first call to toFixed() is unnecessary.
That's because after applying .toFixed() you're adding the value to another variable, which then causes the precision to go haywire again.
Instead use this for displaying:
$('#price'+i).html(companies[i].price.toFixed(2));
The reason it works in your first example is because you are resetting the value of price to 577 on each pass.
Try this, it calls .toFixed(2) on the price after the sum has been calculated and also returns it back to your variable.
You can probably ditch the first .toFixed thats called on randomVal.
window.setInterval(function(){
for(var i=0; i < companies.length; i++) {
var randomVal = (Math.random()*(10 - (-10) + 1)) + (-10);
randomVal = randomVal / 100;
randomVal = Number(randomVal.toFixed(2));
companies[i].price += randomVal;
companies[i].price = Number(companies[i].price.toFixed(2));
$('#price'+i).html(companies[i].price);
}
}, 1000);
your conversion data is response[25] and follow the below steps.
var i = parseFloat(response[25]).toFixed(2)
console.log(i)//-6527.34

toFixed javascript function giving strange results?

I am trying to fix the number to 2 digits after decimal and for that i am using toFixedfunction of javascript. Below are the strange results i am getting, please check and help me.
var number = 11.995;
number.toFixed(2); // giving me 11.99 which is correct
var number = 19.995;
number.toFixed(2); // giving me 20.00 which is incorrect
Can anyone tell me why it is happening.
Thanks for your help.
This is how floating point math works. The value 19.995 is not exact binary (base 2). To make it more clear, think of an exact number when you divide 10/3.
For more in-depth explanations, read this: http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
In your case you can work with strings instead (at least it seems like that is what you want):
number.toString().substr(0, n);
Or define a function like this (made in 2 minutes, just an example):
Number.toFixed = function(no, n) {
var spl = no.toString().split('.');
if ( spl.length > 1 ) {
return spl[0]+'.'+spl[1].substr(0,n);
}
return spl[0];
}
Number.toFixed(19.995, 2); // 19.99
toFixed rounds the value. Since 19.995 is exactly halfway between 19.99 and 20.00, it has to choose one of them. Traditionally, rounding prefers the even result (this prevents bias, since round-ups and round-downs will be equal).
I have create a function which done all for me..
function toFixed(number, precision) {
var multiplier = Math.pow(10, precision + 1),
wholeNumber = Math.floor(number * multiplier);
return Math.round(wholeNumber / 10) * 10 / multiplier;
}
//Call this function to retrive exect value
toFixed((+adjustmentval), 2);
David has answered your doubt I'm guessing. Just providing an alternate solution here.
You can use the Math.floor() method of the Math object for this.
Something like this, Math.floor(number*100)/100
Can anyone tell me why it is happening.
The IEEE-754 double-precision binary floating point number standard used by JavaScript's number type (and similar times in several other languages) does not perfectly store all numbers, it stores some numbers imprecisely, in a way that lets it A) Store them in just 64 bits, and B) Calculate with them quickly.
For 11.995, the actual value is 11.99499988555908203125, just slightly less than 11.995.
For 19.995, the actual value is 19.9950008392333984375, just slightly more than 19.995.
That explains why when you round them using the usual round-to-nearest-half-up operation, 11.995 (which is really 11.99499988555908203125) rounds down to 11.99 but 19.995 (which is really 19.9950008392333984375) rounds up to 20.00.
(This site has a handy calculator for visualizing this stuff.)
More here on SO:
Is floating point math broken?
How to deal with floating point number precision in JavaScript?

How to make 5509.099999999999 as 5509.09 using javascript

How to make 5509.099999999999 as 5509.09 using javascript.
Lots of mathy options that end up with .1 so how about;
var f = 5509.099999999999
if ((f = f.toString()).indexOf(".") >= 0)
f = f.substr(0, 3 + f.indexOf("."))
print(parseFloat(f))
>>5509.09
Have you tried this?
var value = 5509.099999999999;
var str = value.toString();
var result = str.substr(0,7);
Then if you need it to be a float again you can do:
var FinalAnswer = parseFloat(result);
You don't need all these variables, but that is the step by step.
var result = (Math.round((5509.09999 * 100) - 1)) / 100;
You could use .toFixed(2) but this will round the value, so in your example you'll end up with 5509.10 instead of 5509.09.
The next best option is to use Math.floor(), which truncates rather than rounding. Unfortunately, this only gives integer results, so to get the result to 2 decimal places, you'd need to multiply by 100, then use Math.floor(), and then divide by 100 again.
var value = 5509.099999999999;
var result = Math.floor(value*100)/100;
[EDIT]
Hmm, unfortunately, the above doesn't work due to problems with floating point precision -- even just the first step of multiplying it by 100 gives 550910.
Which means that the best answer is likely to be converting it to a string and chopping the string into bits.
var value = 5509.099999999999;
var str_value = value.toString();
var bits = str_value.split('.');
var result = bits[0]+"."+bits[1].substr(0,2);
I wouldn't normally suggest doing string manipulation for this sort of thing, because it is obviously a maths problem, but given the specific requirements of the question, it does seem that this is the only workable solution in this case.
You can truncate the number to a certain number of decimal places using this function:
function truncateNumber(number, digits){
var divisor = Math.pow(10,digits);
return Math.floor(number*divisor)/divisor;
}
If you want to round the number instead, you can use JavaScript's built in Number.toFixed function. If you always want the number a certain number of digits long, you can use the Number.toPrecision function.
if you want to take two decimal places, you can use .toPrecision(n) javascript function, where n is the total number of digits desired.
so, for your example, you'd have to do
var x = 5509.099999999999;
x = x.toPrecision(6);
this, however, rounds results in 5509.10

Categories

Resources