101

I have a variable

var fval = 4;

now I want out put as 4.00

3 Answers 3

157

JavaScript only has a Number type that stores floating point values.

There is no int.

Edit:

If you want to format the number as a string with two digits after the decimal point use:

(4).toFixed(2)
Sign up to request clarification or add additional context in comments.

7 Comments

in php we have function number_format which adds floating points like that do we have any function in javascript
While this does what the question asked for, be careful using toFixed. toFixed returns a string, so if you try to add another number to it, it treats it as a string concatenation, not a number addition.
@AaronGloege Is there a way to keep it as a "number"?
@dollarvar No there isn't. The number type uses a binary floating point representation intended for calculation. It can't distinguish between 4 and 4.00. In fact it can't represent all decimal numbers accurately, but that's a whole nother story.
Use parseFloat(val).toFixed(2); and to keep it number permanently parseFloat(parseFloat(value).toFixed(2));
|
15

toFixed() method formats a number using fixed-point notation. Read MDN Web Docs for full reference.

var fval = 4;

console.log(fval.toFixed(2)); // prints 4.00

1 Comment

YRW. And dont forget to clean up no longer required comments ;-)
-1
var fval = 4;
var fvalfloat = parseFloat(fval).fixed(2)

1 Comment

While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.

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.