0

This is my javascript object and code

buildingJson: {
    name: "build",
    height: 40
}

var val = parseFloat(buildingJson.height).toFixed(2);
buildingJson.height = val;
console.log(typeof buildingJson.height);

This is always logging out a string even though the value is 40.0.

How to set the height to a floating point number in the buildingJson object.

4
  • 2
    Your current code has a syntax error at buildingJson, even if it would be correct then buildingJson is a JavaScript Object, and not JSON. JSON is a textual representation. And it becomes a string because of toFixed MDN: Number.prototype.toFixed(): [...]Returns: A string representation of numObj that does not use exponential notation and has exactly digits digits after the decimal place.[...] Commented Apr 16, 2015 at 22:42
  • Do you know what toFixed() returns? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Apr 16, 2015 at 22:45
  • note: this is not json format valid ..... should you edit and complete your question? Commented Apr 16, 2015 at 22:48
  • 1
    If there is an answer that worked you should accept it. Commented Apr 17, 2015 at 21:07

2 Answers 2

2

That's because toFixed returns a String (that's how the decimals at the end of the number are preserved. To fixed is designed to be used for display purposes.

Removing that will do what you want.

parseFloat(buildingJson.height)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. Will accept answer shortly. How can I add zeros at end and still make it a float ? Do a second float parse after toFixed?
You want to add the zeros for display only right? Just do that right before you display it.
@budhavarapuranga Don't forget to accept the answer. :)
0

toFixed() returns a string in the given precision. If you want a float, don't use toFixed(). See the documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

Comments

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.