Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I format an integer to a specific length in javascript?

I have a number in Javascript, that I know is less than 10000 and also non-negative. I want to display it as a four-digit number, with leading zeroes. Is there anything more elegant than the following?

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

I want something that is built into Javascript, but I can't seem to find anything.

like image 299
Kip Avatar asked Jul 14 '09 20:07

Kip


People also ask

Can you get the length of an integer JavaScript?

Use the toString() method to covert the Number to string, then the length() method gives you length.

How do you format numbers in JavaScript?

JavaScript numbers can be formatted in different ways like commas, currency, etc. You can use the toFixed() method to format the number with decimal points, and the toLocaleString() method to format the number with commas and Intl. NumberFormat() method to format the number with currency.

How do you convert a number to an integer in JavaScript?

In JavaScript parseInt() function (or a method) is used to convert the passed in string parameter or value to an integer value itself. This function returns an integer of base which is specified in second argument of parseInt() function.

What is format for integer?

The integer format is similar to the binary format with two exceptions: The integer format allows the full range of binary values. The number of decimal positions for an integer field is always zero.


2 Answers

The simplest way I can think of is this:

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

A padded number is a string.
When you add a number to a string, it is converted to a string.
Strings has the method slice, that retuns a fixed length piece of the string.
If length is negative the returned string is sliced from the end of the string.

to test:

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

Of cause this only works for positive integers of up to 4 digits. A slightly more complex solution, will handle positive integers:

'0'.repeat( Math.max(4 - num.toString().length, 0)) + num 

Create a string by repeat adding zeros, as long as the number of digits (length of string) is less than 4 Add the number, that is then converted to a string also.

Edit: from now on you should probably use this function:

String(num).padStart(4,'0') 

It still doesn't handle negative numbers...

like image 75
Simon Rigét Avatar answered Sep 27 '22 20:09

Simon Rigét


Since ES2017 padding to a minimum length can be done simply with String.prototype.padStart and String.prototype.padEnd:

let number = 3 let string = number.toString().padStart(3, '0') console.log(string) // "003" 

Or if only the whole part of a float should be a fixed length:

let number = 3.141 let array = number.toString().split('.') array[0] = array[0].padStart(3, '0') let string = array.join('.') console.log(string) // "003.141" 

Neither of these simple uses handle sign, only showing a fraction part when number is not an integer, or other scenarios - so here is a simple example formatting function without options:

function format (number) {     let [ integer, fraction = '' ] = number.toString().split('.')     let sign = ''     if (integer.startsWith('-')) {         integer = integer.slice(1)         sign = '-'     }     integer = integer.padStart(3, '0')     if (fraction) {         fraction = '.' + fraction.padEnd(6, '0')     }     let string = sign + integer + fraction     return string }  console.log(format(3)) // "003" console.log(format(-3)) // "-003" console.log(format(4096)) // "4096" console.log(format(-3.141)) // "-003.141000" 

Although notably this will not handle things that are not numbers, or numbers that toString into scientific notation.

like image 27
spkrtn Avatar answered Sep 27 '22 20:09

spkrtn