Regex separates thousands with commas and stores two decimal places

I recently came up with this code while answering another StackOverflow question. In principle, when blurring, this code will be correctly separated by commas in thousands and leave the decimal digit in two digits (for example, as it is written USD [7,745.56]).

I was wondering if there is a more concise way using regex to split and trim extra decimal places. I recently updated this post with my last attempt. Is there a better way to do this using regex?

Input → Target Output

7456 -> 7,456
45345 -> 45,345
25.23523534 -> 25.23
3333.239 -> 3,333.23
234.99 -> 234.99
2300.99 -> 2,300.99
23123123123.22 -> 23,123,123,123.22

Current rule

var result;
var str = []
reg = new RegExp(/(\d*(\d{2}\.)|\d{1,3})/, "gi");
reversed = "9515321312.2323432".split("").reverse().join("")
while (result = reg.exec(reversed)) {
  str.push(result[2] ? result[2] : result[0])
}
console.log(str.join(",").split("").reverse().join("").replace(",.","."))
Run codeHide result
+4
source share
9 answers

, ( ), , , .replace():

('' + num).replace(
  /(\d)(?=(?:\d{3})+(?:\.|$))|(\.\d\d?)\d*$/g, 
  function(m, s1, s2){
    return s2 || (s1 + ',');
  }
);

:

function format(num){
  return ('' + num).replace(
    /(\d)(?=(?:\d{3})+(?:\.|$))|(\.\d\d?)\d*$/g, 
    function(m, s1, s2){
      return s2 || (s1 + ',');
    }
  );
}


test(7456, "7,456");
test(45345, "45,345");
test(25.23523534, "25.23"); //truncated, not rounded
test(3333.239, "3,333.23"); //truncated, not rounded
test(234.99, "234.99");
test(2300.99, "2,300.99");
test(23123123123.22, "23,123,123,123.22");

function test(num, expected){
  var actual = format(num);
  console.log(num + ' -> ' + expected + ' => ' + actual + ': ' + 
    (actual === expected ? 'passed' : 'failed')
   );
}
Hide result
+4

Regex

Number(num.toFixed(2)).toLocaleString('en-US')

num.toLocaleString('en-US', {maximumFractionDigits: 2})

toFixed(2), . toFixed(2) , . {maximumFractionDigits: 2} toLocaleString.

var nums = [7456, 45345, 25.23523534, 3333.239, 234.99, 2300.99, 23123123123.22]

for (var num of nums) 
  console.log(num, '->',  Number(num.toFixed(2)).toLocaleString('en-US') )
Hide result

, , . - (num * 100 | 0) / 100 . (, 0,99 0,98). ( |0 , Math.floor() ).

, .

function format(num) {
    var num = num.toLocaleString('en-US')
    var end = num.indexOf('.') < 0 ? num.length : num.indexOf('.') + 3
    return num.substring(0, end)
}

var nums = [7456, 45345, 25.23523534, 3333.239, 234.99, 2300.99, 23123123123.22]

for (var num of nums) console.log(num, '->', format(num))

function format(num) {
  var num = num.toLocaleString('en-US')
  var end = num.indexOf('.') < 0 ? num.length : num.indexOf('.') + 3
  return num.substring(0, end)
}
Hide result

( , 'en-US', ., , )

, CanIUse toLocaleString('en-US')

( IE6 +, Firefox 2+, Chrome 1+ ..)

+7

, regex, , ;

val.replace(/(\.\d{2})\d*/, "$1").replace(/(\d)(?=(\d{3})+\b)/g, "$1,")

doIt("7456");
doIt("45345");
doIt("25.23523534");
doIt("3333.239");
doIt("234.99");
doIt("2300.99");
doIt("23123123123.22");
doIt("5812090285.2817481974897");

function doIt(val) {
    console.log(val + " -> " + val.replace(/(\.\d{2})\d*/, "$1").replace(/(\d)(?=(\d{3})+\b)/g, "$1,"));
}
Hide result

, , , , .

+3

Try:

var n = 5812090285.2817481974897;
n = n.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
console.log(n);

:

5,812,090,285.28

: .toFixed(2) a string. , , n string . :

n.toString.replace(/(\d)(?=(\d{3})+\.)/g, '$1,');  //ofc with the additional regex

, javascript, , -, . , "" .

+2

RegEx !

:

.toFixed:

/(\d)(?=(\d\d\d)+(?!\d))/g:

:

// .toFixed((/\./g.test(num)) ? 2 : 0) it tests if the input number has any decimal places, if so limits it to 2 digits and if not, get rid of it altogether by setting it to 0
num.toFixed((/\./g.test(num)) ? 2 : 0).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"))

:

var input = [7456, 45345, 25.23523534, 3333.239, 234.99, 2300.99, 23123123123.22]

input.forEach(function(num) {
  $('div')
    .append(
      $('<p>').text(num + ' => ' +
        num.toFixed( (/\./g.test(num))?2:0 ).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"))
    );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div> </div>
Hide result

. jQuery

+2

:

value.toLocaleString("en-US", { maximumFractionDigits: 2 })

function formatValue() {
    var source = document.getElementById("source");
    var output = document.getElementById("output");
    var value = parseFloat(source.value);
    output.innerText = value.toLocaleString("en-US", { maximumFractionDigits: 2 });
}
<input id="source" type="text" />
<button onclick="formatValue()">Format</button>
<div id="output"></div>
Hide result
+1

Intl.NumberFormat style, "decimal" maximumFractionDigits, 2 options ,

const nums = [7456, 45345, 25.23523534, 3333.239, 234.99, 2300.99, 23123123123.22];

const formatOptions = {style:"decimal", maximumFractionDigits:2};
           
const formatter = new Intl.NumberFormat("en-US", formatOptions);

const formatNums = num => formatter.format(num);

let formattedNums = nums.map(formatNums);

console.log(formattedNums);
Hide result
+1
source

You can do it as follows:

(parseFloat(num).toFixed(2)).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,").replace(".00","")

Here, simply convert the number to a formatted number, rounded to two decimal places, and then remove .00 if they exist.

This may be one approach you can use.

var format = function (num) {
    
return (parseFloat(num).toFixed(2)).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,").replace(".00","")
}
$(function () {
    $("#principalAmtOut").blur(function (e) {
        $(this).val(format($(this).val()));
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="principalAmtOut" type="text" />
Run codeHide result
0
source

I found a solution based on @Pierre's answer without using toFixed:

function format(n) {
  n = +n;
  var d = Math.round(n * 100) % 100;
  return (Math.floor(n) + '').replace(/(\d)(?=(\d{3})+$)/g, '$1,') + (d > 9 ? '.' + d : d > 0 ? '.0' + d : '');
}

console.log(format(7456));
console.log(format(7456.0));
console.log(format(7456.1));
console.log(format(7456.01));
console.log(format(7456.001));
console.log(format(45345));
console.log(format(25.23523534));
console.log(format(3333.239));
console.log(format(234.99));
console.log(format(2300.99));
console.log(format(23123123123.22));
console.log(format('23123123123.22'));
Run codeHide result
0
source

Source: https://habr.com/ru/post/1674549/


All Articles