0

I would like to know if the following line is the correct way to take html and put it into a Javascript var as numeric value?

var thePoolHeatingFeeRounded = Number(document.getElementsById("priceDisplayPoolHeating").innerHTML);

Nevermind that the variable name has the word 'rounded' in it. The value that I am trying to put into this var is a 2 point float that has already been rounded and it exist as html.

Below is the line of HTML code that is referenced by getElementsById...

$<div id="priceDisplayPoolHeating" class="priceDisplay">8.00</div>

Any input is greatly appreciated.

1
  • Yes, this seems right. You will need to check for NaN, unless you have validation in place that takes care of non-numbers. Commented Oct 17, 2014 at 1:00

2 Answers 2

3

Try this instead:

var thePoolHeatingFeeRounded = Number(document.getElementById("priceDisplayPoolHeating").innerHTML);

You were calling getElementsById which is not correct (it is not plural), I changed it to getElementById

Tip: if you need to check whether the Number is valid you can use !isNaN(thePoolHeatingFeeRounded) or use a trick to turn it into a default number (such as 0 or -1) like this:

var thePoolHeatingFeeRounded = Number(document.getElementById("priceDisplayPoolHeating").innerHTML) || 0;

You can also use parseFloat():

var thePoolHeatingFeeRounded = parseFloat(document.getElementById("priceDisplayPoolHeating").innerHTML) || 0;

Sign up to request clarification or add additional context in comments.

1 Comment

Thanx for that info on parseFloat().
1

You are very close. Supposed to be getElementById, not Elements. I created a little code to show you how it works.

Here's what the code looks like in this website's code displayer:

function displayText(){

var thePoolHeatingFeeRounded = Number(document.getElementById("priceDisplayPoolHeating").innerHTML)

  alert(thePoolHeatingFeeRounded);
}
<div id="priceDisplayPoolHeating">8.01</div><input type="button" onclick="displayText()" value="Display the innerHTML of Pool Heating">

7 Comments

Great! Can you tell me why the .00 has been peeled off of the var?
I guess the Number() function requires me to specify 2 point floats?
The Number() function converts the string to function, and reduces it to the simplest form.
Okay, now I'm confused. How'd you get Number() to display the number as a 2 point float without adding any arguments?
What do you mean arguments?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.