728x90
리μ‘νΈμμ number ννμ μ«μλ₯Ό νκ³ λ¨μ ννλ‘ λνλ΄κ³ μΆμλ€.
ex) 1000 μΌ κ²½μ° 1,000 λ‘ λνλ΄κ³ 555666777 μΌ κ²½μ° 555,666,777 λνλ.
case λ₯Ό λκ°μ§λ‘ ꡬλ³νμ¬ κ°λ°ν΄λ³΄μλ€.
input κ°μ΄ "1000" μΌμλ μκ³ 1000 μΌμλ μμΌλ..
CASE1. μ«μ νμ μ λ°μ΄ν°λ₯Ό κ°κ³΅νλ κ²½μ°
Number.prototype.format = function () {
if (this == 0) return 0;
var reg = /(^[+-]?\d+)(\d{3})/;
var n = this + "";
while (reg.test(n)) n = n.replace(reg, "$1" + "," + "$2");
return n;
};
// test
var num = 123456.999;
console.log(num.format()); // 123,456.999
num = 1567895;
console.log(num.format()); // 1,567,895
μμ μλ function μ μ μ¬μ μν κ³³μ 볡λΆν΄μ κ·Έλλ‘ μ¬μ©νλ©΄ λλ€.
CASE2. String(λ¬Έμμ΄) νμ μ λ°μ΄ν°λ₯Ό κ°κ³΅νλ κ²½μ°
Number.prototype.format = function () {
if (this == 0) return 0;
var reg = /(^[+-]?\d+)(\d{3})/;
var n = this + "";
while (reg.test(n)) n = n.replace(reg, "$1" + "," + "$2");
return n;
};
String.prototype.format = function () {
var num = parseFloat(this);
if (isNaN(num)) return "0";
return num.format();
};
// λ¬Έμμ΄ νμ
test
console.log("12348".format()); // 12,348
console.log("12348.6456".format()); // 12,348.6456
stringμ κ²½μ°λ float ννλ‘ νλ³ν ν μμΈ μ²λ¦¬λ₯Ό ν΄μ£Όκ³ , λ€μ number.format functionμΌλ‘ λ겨주λ νν.
μμ μλ function μ μ μ¬μ μν κ³³μ 볡λΆν΄μ κ·Έλλ‘ μ¬μ©νλ©΄ λλ€.
728x90