toFixed(2) function not working - javascript

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

Related

round numbers in js

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.

Find the sum of the digits in the number 100! in javascript

i am getting answer 659 but that one is wrong answer please check it one's.
this is my code
var fact=1;
for(var i=1;i<=100;i++){
fact = fact*i;
}
var sum = 0;
while (fact > 0) {
sum += fact % 10;
fact = Math.floor(fact / 10);
}
console.log(sum);
There's a syntax error in the definition of length - the var keyword should come before it, not after it, and a similar problem in the calculation of sum.
Regardless, I think that converting the number to a string is the hard way to go at it. You can use the % operator to get the last digit and divide the number by 10 (don't forget to floor!) until you're done with all the digits:
var sum = 0;
while (fact > 0) {
sum += fact % 10;
fact = Math.floor(fact / 10);
}
Cool. You've written a very sensible piece of code. But there are a couple things to think about. One is the gigantic size of 100!. If you go to a console and enter some code, you'll see this:
> fact=1
1
> for(i=1;i<=100;i++){fact *= i;}
9.33262154439441e+157
Crikey. 10 to the 157. Look up the largest integer js can display. It's much smaller! So if this is a programming assignment, you have to be more subtle.
Next, if you get the number, all 158 digits, and you want to add them using your strategy, you may need to convert the strings you get (a substring is a string, after all) to a Number.
But really, the question is, can you determine the sum of the digits without calculating the number?

Javascript: "+" sign concatenates instead of giving sum of variables

I am currently creating a site that will help me quickly answer physics questions.
As it happens, the code didn't run as expected, here is the code
if (option == "dv") {
var Vinitial = prompt("What is the Velocity Initial?")
var acceleration = prompt("what is the acceleration?")
var time = prompt("what is the time?")
Vfinal = Vinitial + acceleration * time
displayV.innerHTML = "v= vf= " + Vfinal + "ms" + sup1.sup();
}
Now, let's say Vinitial was 9, acceleration was 2, and time was 3.
When the code runs, instead of getting 15 for "Vfinal", I get 96.
I figured out that it multiplies acceleration and time fine, and then just concatenates the 9 at the beginning, with 6 (the product of 2 * 3).
I have fixed it for now by using
Vfinal = acceleration * time - (-Vinitial)
which avoids using the "+" sign, but I don't want to have to keep doing this. How do I fix it?
you are dealing with strings here, and math operations on strings will mess up. Remember when ever you are doing math operations you have to convert the data into actual numbers and then perform the math.
Use parseInt() more Details here
Your code should change to
Vfinal = parseInt(Vinitial,10) + parseInt(acceleration,10) * parseInt(time,10);
Edit 1: If the numbers are decimal values then use parseFloat() instead
So the code would be
Vfinal = parseFloat(Vinitial) + parseFloat(acceleration) * parseFloat(time);
Object-Oriented JavaScript - Second Edition: As you already know, when you use the plus sign with two numbers, this
is the arithmetic addition operation. However, if you use the plus
sign with strings, this is a string concatenation operation, and it
returns the two strings glued together:
var s1 = "web";
var s2 = "site";
s1 + s2; // website
The dual purpose of the + operator is a source of errors. Therefore,
if you intend to concatenate strings, it's always best to make sure
that all of the operands are strings. The same applies for addition;
if you intend to add numbers, make sure the operands are numbers.
You can use "+" operator with prompt() to convert returned values from string to int
var Vinitial = +prompt("What is the Velocity Initial?");
var acceleration = +prompt("what is the acceleration?");
var time = +prompt("what is the time?");
Explanation:
var a = prompt('Enter a digit');
typeof a; // "string"
typeof +a; // "number"
If you will enter non-digit data +a gives you NaN. typeof NaN is "number" too :)
You will get the same result with parseInt():
var Vinitial = parseInt(prompt("What is the Velocity Initial?"), 10);
var acceleration = parseInt(prompt("what is the acceleration?"), 10);
var time = parseInt(prompt("what is the time?"), 10);
developer.mozilla.org: parseInt(string, radix);
string: The value to parse.
radix: An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the above mentioned string.
Specify 10 for the decimal numeral system commonly used by humans.
Always specify this parameter to eliminate reader confusion and to
guarantee predictable behavior. Different implementations produce
different results when a radix is not specified, usually defaulting
the value to 10.
Epilogue:
Object-Oriented JavaScript - Second Edition: The safest thing to do is to always specify the radix. If you omit the radix, your code
will probably still work in 99 percent of cases (because most often
you parse decimals), but every once in a while it might cause you a
bit of hair loss while debugging some edge cases. For example, imagine
you have a form field that accepts calendar days or months and the
user types 06 or 08.
Epilogue II:
ECMAScript 5 removes the octal literal values and avoids the confusion
with parseInt() and unspecified radix.
The Problem is, Your value has been took it in a form of string .. so convert your value into Int using parseInt(accelaration).. then it will work ..
Vfinal = parseInt(Vinitial) + parseInt(acceleration) * parseInt(time)
//use ParseInt
var a=10,b=10;
var sum=parseInt(a+b);
ex:
parseInt(Vinitial + acceleration) * time

Javascript coding a calculation

I'm coding a price calculator in JS and I'm stuck with one formula:
number = (parseFloat(newnumber, 10) * parseFloat(1.536, 10)).toString(10);
I want to add 7.44 to the value of newnumber, before it is multiplied with 1.536
I've tried several things, but with no success.
Going to submit this as an answer, even though someone has put this up a comment while I was typing my answer.
number = ((+newnumber + 7.44) * 1.536).toString();
That should give you a string representation of the summed value.
Use parentheses to make the addition before the multiplication.
number = ((parseFloat(newnumber) + 7.44) * 1.536).toString();
Notes: parseFloat doesn't have a radix parameter. There is no reason to parse the number 1.536, that will only turn it to a string and then back to the same number again. The default for the radix parameter for toString is 10, so that isn't needed.
number = ((parseFloat(newnumber) + 7.44) * parseFloat(1.536)).toString();?
Just use parentheses to separate out the operations. Simple fix.
Working DEMO
Try the following code -
var newnumber = '1';
var number = ((parseFloat(newnumber) + 7.44) * parseFloat(1.536)).toString(10);
alert(number);

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