0

I have an int, say, var myInt = 24 and I need it to display it as a float like this: 24,000. Is it even possible in javascript?

Important: converted float should be a number, not a string

eZo
  • 373
  • 4
  • 14
  • 2
    JavaScript only has a Number type that stores floating point values.There is no int. – Hamza Zafeer Apr 25 '16 at 14:22
  • 1
    @8protons: Some countries use commas as a decimal mark rather than a point - see https://en.wikipedia.org/wiki/Decimal_mark#Countries_using_Arabic_numerals_with_decimal_comma – Joe Clay Apr 25 '16 at 14:23
  • 1
    "Important: converted float should be a number, not a string" - there is no such thing in JavaScript. A `Number` is a `Number` and can be _represented_ in different ways, depending even on locale. Those representations are strings. Even a `Number` added to the DOM is still a string. It's representation is that returned by `Number.toString()`. – Sergiu Paraschiv Apr 25 '16 at 15:29
  • @Sergiu Paraschiv, thanks! that is what I needed to know – eZo Apr 25 '16 at 15:31

2 Answers2

5

You can use toFixed() to add zeros after the decimal point.

var myInt = 24;
console.log(myInt.toFixed(3));
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
  • Yep, works perfectly! Thanks! I saw that my question is a duplicate thought, so it probably will be deleted :) – eZo Apr 25 '16 at 14:23
  • Actually it is converted to string. It's not what I need :( – eZo Apr 25 '16 at 14:29
  • 2
    Actually, it will be not deleted :) – Legionar Apr 25 '16 at 14:34
  • Yes `toFixed` returns string but you can then use parseFloat and it will return number https://jsfiddle.net/Lg0wyt9u/616/ – Nenad Vracar Apr 25 '16 at 14:34
  • It gives 24 back, not 24.000 :) – eZo Apr 25 '16 at 14:35
  • I need 3 extra zero's at the end, so it will be a float number – eZo Apr 25 '16 at 14:38
  • I don't think its possible https://jsfiddle.net/Lg0wyt9u/618/, if you just have zeros they will be trimmed, unless you use to `toFixed`, and then you can use `parseFloat` again if you need number. – Nenad Vracar Apr 25 '16 at 14:43
  • I'll try to figure out how I can use these two on a project. Thanks! – eZo Apr 25 '16 at 14:50
  • "I need 3 extra zero's at the end, so it will be a float number" - `24` and `24.0` in JavaScript are both `Number` instances. All of them are floats. You can decide to interpret them yourself as integers, but to JavaScript they are all floats. `24.000` is a _representation_ of the float `24`. – Sergiu Paraschiv Apr 25 '16 at 15:31
1

Use Number.toFixed:

var int = 24
document.write('<pre>' + JSON.stringify(int.toFixed(3), 0, 4) + '</pre>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392