jquery - Javascript function to format currency -
i using below function generate formatted comma separated currency value in javascript not working scenarios:
1234 => 1,234 (correct) 1.03 => 1.3 (wrong)
how can fix issue in below function:
function formatthousands(n, dp) { var s = '' + (math.floor(n)), d = n % 1, = s.length, r = ''; while ((i -= 3) > 0) { r = ',' + s.substr(i, 3) + r; } return s.substr(0, + 3) + r + (d ? '.' + math.round(d * math.pow(10, dp || 2)) : ''); }
thanks in advance
to fix code need make sure rest has @ least digits "dp" parameter, if not add leading zeros.
function formatthousands(n, dp) { var s = '' + (math.floor(n)), d = n % 1, = s.length, r = ''; while ((i -= 3) > 0) { r = ',' + s.substr(i, 3) + r; } var rest = math.round(d * math.pow(10, dp || 2)); var rest_len = rest.tostring().length; if(rest_len < dp) { rest = '0'.repeat(dp - rest_len) + rest; } return s.substr(0, + 3) + r + (rest ? '.' + rest : ''); } console.log(formatthousands(1234.14, 2)); //1,234.14 console.log(formatthousands(1.003526, 4)); //1.0035
anyway find cleaner version of thousands separation others mentioned in comments.
Comments
Post a Comment