0

I wanted to document.write the number someone writes on the prompt box with two decimals. But console says "document.write can be a form of eval" and it doesn't appear on the html page, even though I get the prompt for the number.

function roundNumber () {
let myNumber = prompt('Please insert a decimal number.');     
return myNumber.toFixed(2);
}
document.write(roundNumber()); 

Hope someone can help and thanks in advance.

septipo
  • 3
  • 3
  • When you use `document.write()`, what you're writing is parsed as HTML. If it contains Javascript, it will be executed. document.write is 1990's Javascript, learn to use modern coding style. – Barmar Nov 02 '17 at 17:06
  • @Barmar what would be a "modern" document.write() equivalent then? – septipo Nov 02 '17 at 17:17
  • `document.getElementById()` and then setting its `textContent` or `innerHTML` property. – Barmar Nov 02 '17 at 18:30
  • Are you sure you didn't get an error message saying that `myNumber.toFixed` is not a function? – Barmar Nov 02 '17 at 18:33
  • @Barmar what is wrong with using `document.write()` instead of `document.getElementById()` ? I have used both and I find the latter inconvenient for quick testing my code, as I have to create a tag and give it an id. – septipo Nov 02 '17 at 21:43
  • https://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice – Barmar Nov 02 '17 at 21:51

1 Answers1

2

When I run your code, I get the error:

myNumber.toFixed is not a function

Which is expected because the result of prompt is a string not a number, so it doesn't have the toFixed() function. Basically, the problem is that your function has errors and doesn't not run successfully.

If you remove the toFixed() then it works fine:

function roundNumber () {
    let myNumber = prompt('Please insert a decimal number.');     
    return myNumber;
}
document.write(roundNumber()); 

Here is a working example


If you want to work with a decimal number, then you should parse it first using parseFloat. Something like this:

function roundNumber() {
    let myNumber = prompt('Please insert a decimal number.');
    return parseFloat(myNumber).toFixed(2);
}
document.write(roundNumber());

Here is an example

musefan
  • 45,726
  • 20
  • 123
  • 171
  • What does this have to do with the warning he got about `document.write()` being a form of `eval()`? – Barmar Nov 02 '17 at 18:32
  • @Barmar: Well it doesn't, but the code had an error and I fixed that error. Just had to assume the error in the question was from something else not related to this problem. You would have to ask the OP where he got that error from, I am just fixing the code that was provided – musefan Nov 03 '17 at 09:05