97

I have a variable

var fval = 4;

now I want out put as 4.00

om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
Rajesh
  • 999
  • 1
  • 6
  • 3

3 Answers3

151

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)
Alex Jasmin
  • 39,094
  • 7
  • 77
  • 67
  • in php we have function number_format which adds floating points like that do we have any function in javascript – Rajesh Oct 30 '10 at 06:14
  • 8
    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. –  Jun 20 '12 at 15:31
  • @AaronGloege Is there a way to keep it as a "number"? – loveNoHate Dec 14 '13 at 22:49
  • 3
    @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. – Alex Jasmin Dec 18 '13 at 06:10
  • Thanks, I found out though, that calculations with, eehm now I am confused how to call it, numbers with a point are unexactly, so there is no use too keep it as an "integer". ;) – loveNoHate Dec 18 '13 at 06:22
  • 10
    Use `parseFloat(val).toFixed(2);` and to keep it number permanently `parseFloat(parseFloat(value).toFixed(2));` – M.A.K. Ripon Nov 28 '15 at 07:54
  • @M.A.K.Ripon Thanks! Yours should be the accepted answer. – Omar Dulaimi Mar 28 '21 at 16:14
12

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
nkshio
  • 1,060
  • 1
  • 14
  • 23
0
var fval = 4;
var fvalfloat = parseFloat(fval).fixed(2)
Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34
  • 1
    While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) 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. – Yunnosch Feb 13 '23 at 06:27