0

I need convert strings to price format.

For example

  • 150 = 150.00
  • 1000 = 1'000.00
  • 25500 = 25'500.00
  • 1000.80 = 1'000.80 etc.

I wrote code but not sure it is good:

function insert(str, index, value) {
  return str.substr(0, index) + value + str.substr(index);

}

function convert(n) {
  n = n.toString();
  var length = n.length;
  if (length < 4) {
    n = insert(n, length, '.00');
  } else if (length === 4) {
    n = insert(n, 1, "'");
    n = insert(n, length + 1, '.00');

  } else if (length > 4) {
    var floatFlag = false;
    if (n.indexOf('.') > -1 || n.indexOf(',') > -1) {
      floatFlag = true;
      n = n.replace(/,/g, '.');

    }
    var thouthandNumer = n / 1000;
    thouthandNumer = thouthandNumer | 0;
    n = n.replace(thouthandNumer, thouthandNumer + "'");
    if (!floatFlag) {
      n = insert(n, length + 1, '.00');
    }
  }
}
var n = 15000
convert(n); //return 15'000.00

How can I convert strings in correct way? Thanks for help.

Durga
  • 15,263
  • 2
  • 28
  • 52
  • regular epression. Some answer for refrences https://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-dollars-currency-string-in-javascript or there are library available which has more function and formats one of such is accounting.js – bipen Dec 14 '17 at 11:41
  • 1
    If you look at the suggested duplicate [**How can I format numbers as dollars currency string in JavaScript?**](https://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-dollars-currency-string-in-javascript) you can see the solution is flexible in that it should allow you to specify your own separators for decimals and thousand. That would allow you to specify your own separators as needed `d = d == undefined ? "," : d, t = t == undefined ? "." : t,` or use a library as suggested above. – Nope Dec 14 '17 at 11:51

1 Answers1

0

Use Number.toLocaleString():

let x = 25500;
console.log(x.toLocaleString('en-us', {minimumFractionDigits: 2}));
Durga
  • 15,263
  • 2
  • 28
  • 52
raina77ow
  • 103,633
  • 15
  • 192
  • 229
  • It does not provide desired output. – Durga Dec 14 '17 at 11:47
  • Inputs are strings I assume `var x = '25500'; parseInt(x).toLocaleString(...)` or similar would have to be used? – Nope Dec 14 '17 at 11:49
  • UVed. Just replace `,` with `'` afterwards. – Ori Drori Dec 14 '17 at 11:52
  • Thanks, it's amazing. My function: `function convertStringToPrice(n) { n = parseInt(n).toLocaleString('en-us', {minimumFractionDigits: 2}); n =n.replace(/,/g,"'"); return n; }` – Nastya Gorobets Dec 14 '17 at 11:53
  • 1
    @NastyaGorobets You should use your own country's country code, instead of `en-us` instead of replacing separators. Unless your separators are made up then you need the replace. Also, if you care about decimals you need to use `parseFloat()` or similar for `1000.80` or it won't work. – Nope Dec 14 '17 at 12:03