0

Currently output 1844.6304

desired output - comma thousands trim after dot ( no rounding )

1,844 

I was looking some time on forums and can't find a solution to solve both cases.

Kavvson
  • 825
  • 3
  • 9
  • 23
  • Math.floor(1844.6304) it and then follow http://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript – cforcloud Oct 24 '14 at 17:35

3 Answers3

1

Its even simpler like this

var n = 1844.6304,
s =  Math.floor(n).toLocaleString();
console.log(s); //"1,844"
alert(s);
cforcloud
  • 589
  • 2
  • 8
  • That work if you're in the US, but as a Canadian, I see `1 844` – Karl-André Gagnon Oct 24 '14 at 17:47
  • Didn't know that about [Number.prototype.toLocaleString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString) – cforcloud Oct 24 '14 at 17:50
  • @cforcloud Yeah well, it take the local string format and it is set in the computer. You can pass an argument though, maybe you can check if you can force the format? – Karl-André Gagnon Oct 24 '14 at 17:52
1

Try this:

function intWithCommas(x) {
    return Math.floor(x).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

Example:

> intWithCommas(1844.6304)
'1,844'
dug
  • 2,275
  • 1
  • 18
  • 25
0

Try this:

function toCommaInteger(number){
    var result = "" + ~~number;
    var length = result.length;
    var limit = result[0] === "-" ? 1 : 0;
    for(var i = length-3; i > limit; i-=3 ){
        result = result.substring(0,i) + "," + result.substring(i,length);
        length++;
    }
    return result;
}


toCommaInteger(123589.85315)  => 123,589
toCommaInteger(-1289.15315)   => -1,289
toCommaInteger(5)             => 5
Johan Karlsson
  • 6,419
  • 1
  • 19
  • 28