0

is there way to add comma to the thousand digits in numbers?

for example if I have 12345 so I want only the 12,345 also if I have 3215579 so I want only 3,215,579 in my code i do :

{TOTAL.toFixed(0).toLocaleString()}

but it give me just number with no comma inside it and i dont understand whats wrong .

1
  • Avoid asking for different things within single thread and, what's worse, switching directions along the way. Accept answer that was most helpful to trim fractional part and proceed with your another question related to number formatting. Feb 13, 2020 at 13:03

3 Answers 3

1

You could use...

  • Math.trunc() (truncate fractional part, also see below)
  • Math.floor()(round down)
  • Math.ceil() (round up)
  • Math.round() (round to nearest integer)
  • ...dependent on how you wanted to remove the decimal.

Math.trunc() isn't supported on all platforms yet (namely IE), but you could easily use a polyfill in the meantime.

Another method of truncating the fractional portion with excellent platform support is by using a bitwise operator (.e.g |0). The side-effect of using a bitwise operator on a number is it will treat its operand as a signed 32bit integer, therefore removing the fractional component. Keep in mind this will also mangle numbers larger than 32 bits.

0

You can use Math.trunc(). It is also the best way. :)

let a= 123.45 
console.log(Math.trunc(a)) // 123

let b = 3215.579
console.log(Math.trunc(b)) // 3215

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc

0

The best way is to use javascript function toFixed.

suppose you have let a = 123.45;

let b = a.toFixed(0) // will print out 123

To convert to it into comma separated of thousand do ,

b.toLocaleString()

thats it

You can check the docs here : mdn - javascript

Hope it helps. feel free for doubts

4
  • and how do i add a comma in the thousands digit? if i have 45678 so i need to change 45,678 and if i have 67432114 so 67,432,114
    – user12877543
    Feb 13, 2020 at 10:49
  • Now you just have to do , b.toLocaleString(). , thats it
    – Gaurav Roy
    Feb 13, 2020 at 10:53
  • 1
    @miraclark : quick search through SO will find you an answer Feb 13, 2020 at 10:54
  • toLocaleString() doesnt work for me . i do {TOTAL.toLocaleString().toLocaleString()} and its just give me the number with no comma inside.
    – user12877543
    Feb 13, 2020 at 11:12