2009-07-14 13 views
27

Mam numer w JavaScript, który wiem, że jest mniejszy niż 10000, a także nieujemny. Chcę wyświetlić go jako czterocyfrową liczbę z wiodącymi zerami. Czy jest coś bardziej eleganckiego niż poniższe?Jak sformatować liczbę całkowitą na określoną długość w javascript?

if(num<10) num="000"+num; 
else if(num<100) num="00"+num; 
else if(num<1000) num="0"+num; 

Chcę coś, co jest wbudowane w JavaScript, ale nie mogę znaleźć niczego.

Odpowiedz

37

Nie sądzę, aby w języku JavaScript było coś "wbudowanego" w ten sposób. Oto prosta funkcja, która wykonuje to:

function FormatNumberLength(num, length) { 
    var r = "" + num; 
    while (r.length < length) { 
     r = "0" + r; 
    } 
    return r; 
} 


FormatNumberLength(10000, 5) outputs '10000' 
FormatNumberLength(1000, 5) outputs '01000' 
FormatNumberLength(100, 5) outputs '00100' 
FormatNumberLength(10, 5) outputs '00010' 
+6

wolałbym nazwać num Metoda .toString(). – SolutionYogi

15

To może pomóc:

String.prototype.padLeft = function (length, character) { 
    return new Array(length - this.length + 1).join(character || '0') + this; 
} 

var num = '12'; 

alert(num.padLeft(4, '0')); 
0

Można oszaleć z metody takie jak:

function PadDigits(input, totalDigits) 
{ 
    var result = input; 
    if (totalDigits > input.length) 
    { 
     for (i=0; i < (totalDigits - input.length); i++) 
     { 
      result = '0' + result; 
     } 
    } 
    return result; 
} 

Ale to nie będzie ułatwienie życia . C# ma metodę jak PadLeft i PadRight w klasy String, niestety Javascript nie posiada tej funkcji build-in

1

Jak o coś takiego:

function prefixZeros(number, maxDigits) 
{ 
    var length = maxDigits - number.toString().length; 
    if(length <= 0) 
     return number; 

    var leadingZeros = new Array(length + 1); 
    return leadingZeros.join('0') + number.toString(); 
} 
//Call it like prefixZeros(100, 5); //Alerts 00100 
6

zabawny (ale ciekawe) sposób prefiks liczby z zerami:

function FormatInteger(num, length) { 

    return (num/Math.pow(10, length)).toFixed(length).substr(2); 
} 
+0

'funkcja FormatInteger (n, l, c) {return (n/Math.pow (10, l)) .Fixed (l) .substr (2) .replace (/ 0/g, c || ''); } '... ' console.log (FormatInteger (432,8)); ' –

0

Pętla "while" powinna to ułatwić.

function formatLength(a) { 
    var num = document.getElementById(a) 
    while (num.value.length < 4) { 
     num.value = '0' + num.value 
    } 
} 

że pętli aż długość wartości num osiągnęła 4 cyfry (zakładając, że minęło w id elementu numer jako argument)

0

wpadłem na taki sam błąd i I znalazł zwarty sposób, aby go rozwiązać. Gdybym musiał użyć go wielokrotnie w moim kodzie lub gdy robiłbym to dla więcej niż czterech cyfr, użyłbym jednego z innych sugerowanych rozwiązań, ale w ten sposób mogę umieścić to wszystko w wyrażeniu:

((x<10)?"000": (x<100)?"00": (x<1000)?"0": "") + x 

W rzeczywistości jest to ten sam kod, ale za pomocą operatora potrójnego zamiast instrukcji "if-else" (i przenoszenie "+ x", który zawsze będzie częścią wyrażenia, poza kodem warunkowym).

48

Najprostszym sposobem, myślę, jest to:

("000" + num).slice(-4) 

Szereg wyściełany jest ciągiem.
Po dodaniu numeru do ciągu jest on konwertowany na ciąg znaków.
Ciągi mają wycinek metody, który retunuje kawałek długości o stałej długości.
Jeśli długość jest ujemna, zwraca się od końca.

do testu:

var num=12; 
console.log(("000" + num).slice(-4)); // Will show "0012" 

(Of powodować ten działa tylko dla liczb całkowitych dodatnich dla maksymalnie 4 cyfry)

+2

To jest tak niesamowicie proste. Kciuki w górę –

+0

Dobra sztuczka. Ale trochę niebezpieczne dla liczb z więcej niż 4 cyframi ... – Remo

0

jeszcze jeden:

function format_number_length(num, length) { 
    var r = num.toString(); 
    if (r.length<length) r = Array(length - r.length + 1).join('0') + r; 
    return r; 
} 
2

Myślę, że najbardziej kompaktowy jeszcze intuicyjny jest następujący:

function toFixedLength(input, length, padding) { 
    padding = String(padding || "0"); 
    return (padding.repeat(length) + input).slice(-length); 
} 

T Metoda ta może być zastąpiona przez substr, jeśli jest ona bardziej intuicyjna dla kodera.

1

Szukałem odpowiedzi, ale myślę, że jest to lepsze funkcjonalne podejście (ES6):

const formatNumberToString = (num, minChars) => { 
    return num.toString().length < minChars 
    ? formatNumberToString(`0${num}`, minChars) 
    : num.toString() 
} 
// formatNumberToString(12, 4) // "0012" 
// formatNumberToString(12, 5) // "00012" 
// formatNumberToString(1, 4) // "0001" 
// formatNumberToString(1, 2) // "01" 
// formatNumberToString(12, 2) // "12" 
// formatNumberToString(12, 1) // "12" 

również, to mogą być realizowane tylko w jednej linii

Powiązane problemy