1

I have tried using Number(x).toLocaleString(), but this only gives me 10,000.

When I use parseFloat(row.profit).toFixed(2) it gives me 10000.00. I tried combining parseFloat(Number(row.profit)toLocaleString()).toFixed(2) But not give me the desired output which should be 10,000.00. How can I achieve this?

c.k
  • 1,075
  • 1
  • 18
  • 35
  • look at the specs for toLocaleString. `minimumFractionDigits` is an option you can set. – user3154108 Jul 12 '16 at 06:53
  • OK, so you didn't ask about money, but if you ignore the dollar sign the linked duplicate is asking the same thing about the commas and decimals, and e.g., [this answer](http://stackoverflow.com/a/149099/615754) does it with a fairly short function. – nnnnnn Jul 12 '16 at 06:56
  • Consider the answers to [*How to format numbers using JavaScript?*](http://stackoverflow.com/questions/5882994/how-to-format-numbers-using-javascript/5884019#5884019), which uses *toLocaleString* to determine whether to use "," for thousands and "." for decimal or *vice versa*. – RobG Jul 12 '16 at 06:59
  • 1
    @nnnnnn the link answer is delete please check – guradio Jul 12 '16 at 06:59
  • 1
    @guradio - Sorry, I accidentally double-pasted the URL in my link. Have edited my previous comment to fix it. – nnnnnn Jul 12 '16 at 07:01

1 Answers1

1

You can use a quick hack by testing if . is present in your locale string or not :

function localeFormat(x) {
  var num = Number(x).toLocaleString();
  if (num.indexOf("/.") > 0) {
    num += ".00";
  }else{
    var n = parseFloat(x).toFixed(2).toString();  
    num = Number(n).toLocaleString();
  }
  return num;
}
var strs = ["10000", "10000.45", "10000.45768"];
for(var i = 0; i < strs.length; i++){
  console.log(strs[i] + " -> " + localeFormat(strs[i]));
}
Himanshu Tyagi
  • 5,201
  • 1
  • 23
  • 43