javascript number_format A value different from the expected value is output...

Asked 2 years ago, Updated 2 years ago, 41 views

Input value variable price = 6811.15;

var strPrice = number_format(parseFloat(price),2);
console.log(strPrice); // 6,811,.15

Invalid value 6811.15 -> number_format -> 6,811,15

Expected value 6811.15 -> number_format -> 6,811.15

The value is strange even if you apply Math.round and .fixed(2) in this way.

javascript jquery html

2022-09-22 16:55

1 Answers

Is number_format a self-made function?

Do it like this.

Number.prototype.numberFormat = function(c){
var n = this, 
    c = isNaN(c = Math.abs(c)) ? 2 : c, 
    s = n < 0 ? "-" : "", 
    i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", 
    j = (j = i.length) > 3 ? j % 3 : 0;
   return s + (j ? (i.substr(0, j) + ",") : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + ",") + (c ? "." + Math.abs(n - i).toFixed(c).slice(2) : "");
 };

var price = 6811.15;
var strPrice = (6811.15).numberFormat(2)
console.log(strPrice); // 6,811,.15


2022-09-22 16:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.