Nice programing

C #과 유사한 JavaScript에서 숫자 형식 지정

nicepro 2020. 10. 25. 13:04
반응형

C #과 유사한 JavaScript에서 숫자 형식 지정


를 통해 C # (또는 VB.NET)에서 사용할 수있는 포맷 방법과 유사한 자바 스크립트의 형식 번호에 대한 간단한 방법 있나요 ToString("format_provider")또는 String.Format()?


아마도 JQuery NUMBERFORMATTER 플러그인을 살펴 봐야합니다.

Jquery 숫자 포맷터

그리고이 질문 :

숫자 형식을 지정하는 더 쉬운 방법


일반적으로

jQuery에서


예, 확실히 자바 스크립트에서 숫자 형식을 올바르게 지정하는 방법이 있습니다. 예 :

var val=2489.8237

val.toFixed(3) //returns 2489.824 (round up)
val.toFixed(2) //returns 2489.82
val.toFixed(7) //returns 2489.8237000 (padding)

variablename을 사용합니다. toFixed .

그리고 또 다른 기능이 toPrecision()있습니다. 자세한 내용은 다음을 방문하십시오.

http://raovishal.blogspot.com/2012/01/number-format-in-javascript.html


다음은 문자열 형식의 정수에 쉼표를 추가하는 간단한 JS 함수입니다. 정수 또는 십진수를 처리합니다. 숫자 또는 문자열로 전달할 수 있습니다. 분명히 문자열을 반환합니다.

function addCommas(str) {
    var parts = (str + "").split("."),
        main = parts[0],
        len = main.length,
        output = "",
        first = main.charAt(0),
        i;

    if (first === '-') {
        main = main.slice(1);
        len = main.length;    
    } else {
        first = "";
    }
    i = len - 1;
    while(i >= 0) {
        output = main.charAt(i) + output;
        if ((len - i) % 3 === 0 && i > 0) {
            output = "," + output;
        }
        --i;
    }
    // put sign back
    output = first + output;
    // put decimal part back
    if (parts.length > 1) {
        output += "." + parts[1];
    }
    return output;
}

다음은 일련의 테스트 사례입니다. http://jsfiddle.net/jfriend00/6y57j/

이전 jsFiddle에서 사용중인 것을 볼 수 있습니다 : http://jsfiddle.net/jfriend00/sMnjT/ . "javascript add commas"에 대한 간단한 Google 검색으로 십진수를 처리하는 함수도 찾을 수 있습니다.

숫자를 문자열로 변환하는 방법은 여러 가지가 있습니다. 가장 쉬운 방법은 문자열에 추가하는 것입니다.

var myNumber = 3;
var myStr = "" + myNumber;   // "3"

jsFiddle 컨텍스트 내에서 다음 줄을 변경하여 카운터에 쉼표를 입력합니다.

jTarget.text(current);

이에:

jTarget.text(addCommas(current));

여기에서 작동하는 것을 볼 수 있습니다 : http://jsfiddle.net/jfriend00/CbjSX/


나는 숫자를 10 진수로 구분 된 문자열 또는 숫자가 시작할 숫자가 아닌 경우 빈 문자열로 변환하는 간단한 함수 (아직 다른 jQuery 플러그인이 필요하지 않습니다 !!)를 작성했습니다.

function format(x) {
    return isNaN(x)?"":x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

format(578999); 결과 578,999

format(10); 결과 10

쉼표 대신 소수점을 사용하려면 코드의 쉼표를 소수점으로 바꾸면됩니다.

주석 중 하나는 이것이 정수에서만 작동한다고 올바르게 언급했으며 몇 가지 작은 조정을 통해 부동 소수점에서도 작동하도록 만들 수 있습니다.

function format(x) {
    if(isNaN(x))return "";

    n= x.toString().split('.');
    return n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",")+(n.length>1?"."+n[1]:"");
}

여기 몇 가지 솔루션이 있습니다. 모두 테스트 도구 모음, 테스트 도구 모음 및 벤치 마크를 통과했습니다. 복사하여 붙여 넣기를 테스트하려면 This Gist를 사용 해보세요 .

방법 0 (RegExp)

https://stackoverflow.com/a/14428340/1877620을 기반으로 하지만 소수점이없는 경우 수정합니다.

if (typeof Number.prototype.format === 'undefined') {
    Number.prototype.format = function (precision) {
        if (!isFinite(this)) {
            return this.toString();
        }

        var a = this.toFixed(precision).split('.');
        a[0] = a[0].replace(/\d(?=(\d{3})+$)/g, '$&,');
        return a.join('.');
    }
}

방법 1

if (typeof Number.prototype.format1 === 'undefined') {
    Number.prototype.format1 = function (precision) {
        if (!isFinite(this)) {
            return this.toString();
        }

        var a = this.toFixed(precision).split('.'),
            // skip the '-' sign
            head = Number(this < 0);

        // skip the digits that's before the first thousands separator 
        head += (a[0].length - head) % 3 || 3;

        a[0] = a[0].slice(0, head) + a[0].slice(head).replace(/\d{3}/g, ',$&');
        return a.join('.');
    };
}

방법 2 (배열로 분할)

if (typeof Number.prototype.format2 === 'undefined') {
    Number.prototype.format2 = function (precision) {
        if (!isFinite(this)) {
            return this.toString();
        }

        var a = this.toFixed(precision).split('.');

        a[0] = a[0]
            .split('').reverse().join('')
            .replace(/\d{3}(?=\d)/g, '$&,')
            .split('').reverse().join('');

        return a.join('.');
    };
}

방법 3 (루프)

if (typeof Number.prototype.format3 === 'undefined') {
    Number.prototype.format3 = function (precision) {
        if (!isFinite(this)) {
            return this.toString();
        }

        var a = this.toFixed(precision).split('');
        a.push('.');

        var i = a.indexOf('.') - 3;
        while (i > 0 && a[i-1] !== '-') {
            a.splice(i, 0, ',');
            i -= 3;
        }

        a.pop();
        return a.join('');
    };
}

console.log('======== Demo ========')
var n = 0;
for (var i=1; i<20; i++) {
    n = (n * 10) + (i % 10)/100;
    console.log(n.format(2), (-n).format(2));
}

분리 기호

사용자 정의 천 단위 구분 기호 또는 소수 구분 기호를 원한다면 replace ()를 사용하십시오.

123456.78.format(2).replace(',', ' ').replace('.', ' ');

테스트 스위트

function assertEqual(a, b) {
    if (a !== b) {
        throw a + ' !== ' + b;
    }
}

function test(format_function) {
    console.log(format_function);
    assertEqual('NaN', format_function.call(NaN, 0))
    assertEqual('Infinity', format_function.call(Infinity, 0))
    assertEqual('-Infinity', format_function.call(-Infinity, 0))

    assertEqual('0', format_function.call(0, 0))
    assertEqual('0.00', format_function.call(0, 2))
    assertEqual('1', format_function.call(1, 0))
    assertEqual('-1', format_function.call(-1, 0))
    // decimal padding
    assertEqual('1.00', format_function.call(1, 2))
    assertEqual('-1.00', format_function.call(-1, 2))
    // decimal rounding
    assertEqual('0.12', format_function.call(0.123456, 2))
    assertEqual('0.1235', format_function.call(0.123456, 4))
    assertEqual('-0.12', format_function.call(-0.123456, 2))
    assertEqual('-0.1235', format_function.call(-0.123456, 4))
    // thousands separator
    assertEqual('1,234', format_function.call(1234.123456, 0))
    assertEqual('12,345', format_function.call(12345.123456, 0))
    assertEqual('123,456', format_function.call(123456.123456, 0))
    assertEqual('1,234,567', format_function.call(1234567.123456, 0))
    assertEqual('12,345,678', format_function.call(12345678.123456, 0))
    assertEqual('123,456,789', format_function.call(123456789.123456, 0))
    assertEqual('-1,234', format_function.call(-1234.123456, 0))
    assertEqual('-12,345', format_function.call(-12345.123456, 0))
    assertEqual('-123,456', format_function.call(-123456.123456, 0))
    assertEqual('-1,234,567', format_function.call(-1234567.123456, 0))
    assertEqual('-12,345,678', format_function.call(-12345678.123456, 0))
    assertEqual('-123,456,789', format_function.call(-123456789.123456, 0))
    // thousands separator and decimal
    assertEqual('1,234.12', format_function.call(1234.123456, 2))
    assertEqual('12,345.12', format_function.call(12345.123456, 2))
    assertEqual('123,456.12', format_function.call(123456.123456, 2))
    assertEqual('1,234,567.12', format_function.call(1234567.123456, 2))
    assertEqual('12,345,678.12', format_function.call(12345678.123456, 2))
    assertEqual('123,456,789.12', format_function.call(123456789.123456, 2))
    assertEqual('-1,234.12', format_function.call(-1234.123456, 2))
    assertEqual('-12,345.12', format_function.call(-12345.123456, 2))
    assertEqual('-123,456.12', format_function.call(-123456.123456, 2))
    assertEqual('-1,234,567.12', format_function.call(-1234567.123456, 2))
    assertEqual('-12,345,678.12', format_function.call(-12345678.123456, 2))
    assertEqual('-123,456,789.12', format_function.call(-123456789.123456, 2))
}

console.log('======== Testing ========');
test(Number.prototype.format);
test(Number.prototype.format1);
test(Number.prototype.format2);
test(Number.prototype.format3);

기준

function benchmark(f) {
    var start = new Date().getTime();
    f();
    return new Date().getTime() - start;
}

function benchmark_format(f) {
    console.log(f);
    time = benchmark(function () {
        for (var i = 0; i < 100000; i++) {
            f.call(123456789, 0);
            f.call(123456789, 2);
        }
    });
    console.log(time.format(0) + 'ms');
}

async = [];
function next() {
    setTimeout(function () {
        f = async.shift();
        f && f();
        next();
    }, 10);
}

console.log('======== Benchmark ========');
async.push(function () { benchmark_format(Number.prototype.format); });
async.push(function () { benchmark_format(Number.prototype.format1); });
async.push(function () { benchmark_format(Number.prototype.format2); });
async.push(function () { benchmark_format(Number.prototype.format3); });
next();

jQuery를 사용하지 않으려면 Numeral.js를 살펴보십시오.


첫째, JS에서 정수를 문자열로 변환하는 것은 정말 간단합니다.

// Start off with a number
var number = 42;
// Convert into a string by appending an empty (or whatever you like as a string) to it
var string = 42+'';
// No extra conversion is needed, even though you could actually do
var alsoString = number.toString();

숫자를 문자열로 사용하고 정수로 바꾸려면 parseInt(string)정수 및 parseFloat(string)부동 소수점에 를 사용해야합니다 . 이 두 함수 모두 원하는 정수 / 부동 소수점을 반환합니다. 예:

// Start off with a float as a string
var stringFloat = '3.14';
// And an int as a string
var stringInt = '42';

// typeof stringInt  would give you 'string'

// Get the real float from the string
var realFloat = parseFloat(someFloat);
// Same for the int
var realInt = parseInt(stringInt);

// but typeof realInt  will now give you 'number'

등을 추가하려고 정확히 무엇을 시도하고 있습니까? 귀하의 질문에서 나에게 명확하지 않습니다.


http://code.google.com/p/javascript-number-formatter/ :

  • 짧고 빠르며 유연하지만 독립형입니다. MIT 라이센스 정보, 빈 줄 및 주석을 포함하여 75 줄만 있습니다.
  • #, ## 0.00 또는 부정 -000. ####과 같은 표준 숫자 형식을 허용합니다.
  • # ## 0,00, #, ###. ##, # '###. ##과 같은 모든 국가 형식 또는 번호가없는 기호 유형을 허용합니다.
  • 숫자 그룹화를 허용합니다. #, ##, # 0.000 또는 #, ### 0. ## 모두 유효합니다.
  • 중복 / 완벽한 형식을 허용합니다. ##, ###, ##. # 또는 0 #, # 00 #. ### 0 # 모두 괜찮습니다.
  • 자동 숫자 반올림.
  • 간단한 인터페이스, 다음과 같은 마스크 및 값 제공 : format ( "0.0000", 3.141592)

최신 정보

Tomáš Zato가 여기에 한 줄 솔루션 이라고 말하면 다음과 같습니다.

(666.0).toLocaleString()
numObj.toLocaleString([locales [, options]])

ECMA-262 5.1 Edition에 설명 된 내용 :

향후 버전의 브라우저에서 작동합니다 ...


예를 들면 :

var flt = '5.99';
var nt = '6';

var rflt = parseFloat(flt);
var rnt = parseInt(nt);

JQuery 사용 .

$(document).ready(function()
 {
    //Only number and one dot
    function onlyDecimal(element, decimals)
    {
        $(element).keypress(function(event)
        {
            num = $(this).val() ;
            num = isNaN(num) || num === '' || num === null ? 0.00 : num ;
            if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57))
            {
                event.preventDefault();

            }
            if($(this).val() == parseFloat(num).toFixed(decimals))
            {
                event.preventDefault();
            }
        });
    }

     onlyDecimal("#TextBox1", 3) ;



});


쉼표 뒤에 2 개의 숫자가있는 십진수를 얻으려면 다음을 사용할 수 있습니다.

function nformat(a) {
   var b = parseInt(parseFloat(a)*100)/100;
   return b.toFixed(2);
}

다음은 다른 버전입니다.

$.fn.digits = function () {
    return this.each(function () {
        var value = $(this).text();
        var decimal = "";
        if (value) {
            var pos = value.indexOf(".");
            if (pos >= 0) {
                decimal = value.substring(pos);
                value = value.substring(0, pos);
            }
            if (value) {
                value = value.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
                if (!String.isNullOrEmpty(decimal)) value = (value + decimal);
                $(this).text(value);
            }
        }
        else {
            value = $(this).val()
            if (value) {
                var pos = value.indexOf(".");
                if (pos >= 0) {
                    decimal = value.substring(pos);
                    value = value.substring(0, pos);
                }
                if (value) {
                    value = value.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
                    if (!String.isNullOrEmpty(decimal)) value = (value + decimal);
                    $(this).val(value);
                }
            }
        }
    })
};

간단한 기능을 만들었는데 누군가가 사용할 수 있을지도 몰라요

function secsToTime(secs){
  function format(number){
    if(number===0){
      return '00';
    }else {
      if (number < 10) {
          return '0' + number
      } else{
          return ''+number;
      }
    }
  }

  var minutes = Math.floor(secs/60)%60;
  var hours = Math.floor(secs/(60*60))%24;
  var days = Math.floor(secs/(60*60*24));
  var seconds = Math.floor(secs)%60;

  return (days>0? days+"d " : "")+format(hours)+':'+format(minutes)+':'+format(seconds);
}

이것은 다음과 같은 출력을 생성 할 수 있습니다.

  • 5 일 02:53:39
  • 4d 22:15:16
  • 03:01:05
  • 00:00:00

계산이 아닌보기를 위해 숫자를 형식화하려면 이것을 사용할 수 있습니다.

function numberFormat( number ){

    var digitCount = (number+"").length;
    var formatedNumber = number+"";
    var ind = digitCount%3 || 3;
    var temparr = formatedNumber.split('');

    if( digitCount > 3 && digitCount <= 6 ){

        temparr.splice(ind,0,',');
        formatedNumber = temparr.join('');

    }else if (digitCount >= 7 && digitCount <= 15) {
        var temparr2 = temparr.slice(0, ind);
        temparr2.push(',');
        temparr2.push(temparr[ind]);
        temparr2.push(temparr[ind + 1]);
        // temparr2.push( temparr[ind + 2] ); 
        if (digitCount >= 7 && digitCount <= 9) {
            temparr2.push(" million");
        } else if (digitCount >= 10 && digitCount <= 12) {
            temparr2.push(" billion");
        } else if (digitCount >= 13 && digitCount <= 15) {
            temparr2.push(" trillion");

        }
        formatedNumber = temparr2.join('');
    }
    return formatedNumber;
}

입력 : {Integer} 숫자

Outputs: {String} Number

22,870 => if number 22870

22,87 million => if number 2287xxxx (x can be whatever)

22,87 billion => if number 2287xxxxxxx

22,87 trillion => if number 2287xxxxxxxxxx

You get the idea


To further jfriend00's answer (I dont't have enough points to comment) I have extended his/her answer to the following:

function log(args) {
    var str = "";
    for (var i = 0; i < arguments.length; i++) {
        if (typeof arguments[i] === "object") {
            str += JSON.stringify(arguments[i]);
        } else {
            str += arguments[i];
        }
    }
    var div = document.createElement("div");
    div.innerHTML = str;
    document.body.appendChild(div);
}

Number.prototype.addCommas = function (str) {
    if (str === undefined) {
    	str = this;
    }
    
    var parts = (str + "").split("."),
        main = parts[0],
        len = main.length,
        output = "",
        first = main.charAt(0),
        i;
    
    if (first === '-') {
        main = main.slice(1);
        len = main.length;    
    } else {
    	  first = "";
    }
    i = len - 1;
    while(i >= 0) {
        output = main.charAt(i) + output;
        if ((len - i) % 3 === 0 && i > 0) {
            output = "," + output;
        }
        --i;
    }
    // put sign back
    output = first + output;
    // put decimal part back
    if (parts.length > 1) {
        output += "." + parts[1];
    }
    return output;
}

var testCases = [
    1, 12, 123, -1234, 12345, 123456, -1234567, 12345678, 123456789,
    -1.1, 12.1, 123.1, 1234.1, -12345.1, -123456.1, -1234567.1, 12345678.1, 123456789.1
];
 
for (var i = 0; i < testCases.length; i++) {
	log(testCases[i].addCommas());
}
 
/*for (var i = 0; i < testCases.length; i++) {
    log(Number.addCommas(testCases[i]));
}*/


May I suggest numbro for locale based formatting and number-format.js for the general case. A combination of the two depending on use-case may help.

참고URL : https://stackoverflow.com/questions/1068284/format-numbers-in-javascript-similar-to-c-sharp

반응형