I am taking practice exercises and ran into this issue.
This problem asks:
“Prompt for a number greater than 1 and to 4 decimal places. Format
and write the number to the page displaying with only 2 digits past
the decimal point using the toFixed() method. (e.g. 12.35, not
12.3453)Since this method is very new, it doesn’t work in older browsers. See
if you can get only 2 digits past the decimal point to show without
using toFixed().”
I found the answer to the hard part through the archives here, Math.round(n*100)/100. Thanks for that. But when I tried the “easy” way, I get nothing. My work is at jsFiddle, but in a nutshell:
var num = prompt("Give me a number greater than one, with 4 decimal places.");
var num2 = prompt("Great! Do one more, please!");
num = Math.round(num*100)/100;
num2 = num2.toFixed(2);
alert(num);
alert(num2);
The exercise did not ask for a second number, but I wanted to use both methods in separate incidences. When I run this it does not alert anything. I know that it is hanging at the toFixed statement, because when I comment it out it alerts both as expected, num1 at 2 decimal places, and num2 as it was prompted (i.e. 1.2345).
So here is what I have done so far:
Mozilla’s developer page shows this format: n.toFixed(1);// Returns “12345.7”: note rounding
Seems exactly what I am doing.
I copied and pasted all of it in my Sublime, making sure that I called the .js file just before the closing body tag, to make sure it wasn’t some loading problem I don’t understand.
Plus all sorts of little tweaking.
Sorry to keep asking these questions, but since I am self-study, I have where else to go!
You need to use
parseFloat. Using the function will convert the string to a float type variable, allowing for thetoFixedfunction to work properly.