2

I use the following function to format numbers:

function formatNumber(value, precision) {
    if (Number.isFinite(value)) {
        // Source: kalisjoshua's comment to VisioN's answer in the following stackoverflow question:
        // http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript
        return value.toFixed(precision || 0).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, "$1,")
    } else {
        return ""
    }
}

The above works except one case:

1130.000200 becomes 1,130.000,200

but I need

1130.000200 become 1,130.000200

It seems I need negative lookbehind ?<!, i.e. match a digit not preceded by dot, but how?

EDIT: As answered in this question, Number.prototype.toLocaleString() is a good solution for newer browsers. I need to support IE10, so leave this question as it is here.

synergetic
  • 7,756
  • 8
  • 65
  • 106
  • I recommend you the lib [wNumb.js](https://refreshless.com/wnumb/), to format number. – R3tep Jun 02 '17 at 08:06
  • Possible duplicate of [Javascript Thousand Separator / string format](https://stackoverflow.com/questions/3753483/javascript-thousand-separator-string-format) – Emissary Jun 02 '17 at 08:07
  • 1
    Use `Intl.NumberFormat`. –  Jun 03 '17 at 10:56

3 Answers3

0

Simply remove ? in after the .Match. updated pattern is /(\d)(?=(\d{3})+(?:\.\d+)$)/g,

? Quantifier — Matches between zero and one times, as many times as possible, giving back as needed

Demo regex and explanation

console.log('1130.000200'.replace(/(\d)(?=(\d{3})+(?:\.\d+)$)/g, "$1,"))
prasanth
  • 22,145
  • 4
  • 29
  • 53
0

Made it work with code below.

The key is to match decimal point which is variable d. If not matches, don't replace.

function formatNumber(value, precision) {
    var regex = /(\d)(?=(\d{3})+(?:(\.)\d+)?$)/g;
    return (+value).toFixed(precision || 0).replace(regex, function(a, b, c, d) {
            return d ? b+',' : b;
        });
}

console.log(formatNumber(1130.000200, 6));
console.log(formatNumber(1130, 6));

Example from regex101, you'll see decimal point matches into Group 3. https://regex101.com/r/qxriNx/1

Val
  • 21,938
  • 10
  • 68
  • 86
  • Got upvote once, and downvote once. Leave a comment please so I can improve my answer. – Val Jun 05 '17 at 05:33
0

You can use this simple function to format your decimal numbers:

function fmt(num) {
   // split into two; integer and fraction part
   var arr = num.match(/^(\d+)((?:\.\d+)?)$/);

   // format integer part and append fraction part
   return arr[1].replace(/(\d)(?=(?:\d{3})+$)/g, '$1,') + arr[2];
}

var s1 = fmt('1130.000200')
//=> "1,130.000200"

var s2 = fmt('1130000200')
//=> "1,130,000,200"
anubhava
  • 761,203
  • 64
  • 569
  • 643