I want to format a number to have two digits. The problem is caused when 0
–9
is passed, so I need it to be formatted to 00
–09
.
Is there a number formatter in JavaScript?
It's no longer necessary to format numbers by hand like this anymore. This answer was written way-back-when in the distant year of 2011 when IE was important and babel and bundlers were just a wonderful, hopeful dream.
I think it would be a mistake to delete this answer; however in case you find yourself here, I would like to kindly direct your attention to the second highest voted answer to this question as of this edit.
It will introduce you to the use of .toLocaleString()
with the options parameter of {minimumIntegerDigits: 2}
. Exciting stuff. Below I've recreated all three examples from my original answer using this method for your convenience.
[7, 7.5, -7.2345].forEach(myNumber => {
let formattedNumber = myNumber.toLocaleString('en-US', {
minimumIntegerDigits: 2,
useGrouping: false
})
console.log(
'Input: ' + myNumber + '\n' +
'Output: ' + formattedNumber
)
})
The best method I've found is something like the following:
(Note that this simple version only works for positive integers)
var myNumber = 7;
var formattedNumber = ("0" + myNumber).slice(-2);
console.log(formattedNumber);
For decimals, you could use this code (it's a bit sloppy though).
var myNumber = 7.5;
var dec = myNumber - Math.floor(myNumber);
myNumber = myNumber - dec;
var formattedNumber = ("0" + myNumber).slice(-2) + dec.toString().substr(1);
console.log(formattedNumber);
Lastly, if you're having to deal with the possibility of negative numbers, it's best to store the sign, apply the formatting to the absolute value of the number, and reapply the sign after the fact. Note that this method doesn't restrict the number to 2 total digits. Instead it only restricts the number to the left of the decimal (the integer part). (The line that determines the sign was found here).
var myNumber = -7.2345;
var sign = myNumber?myNumber<0?-1:1:0;
myNumber = myNumber * sign + ''; // poor man's absolute value
var dec = myNumber.match(/\.\d+$/);
var int = myNumber.match(/^[^\.]+/);
var formattedNumber = (sign < 0 ? '-' : '') + ("0" + int).slice(-2) + (dec !== null ? dec : '');
console.log(formattedNumber);
Here's a simple number padding function that I use usually. It allows for any amount of padding.
function leftPad(number, targetLength) {
var output = number + '';
while (output.length < targetLength) {
output = '0' + output;
}
return output;
}
Examples:
leftPad(1, 2) // 01
leftPad(10, 2) // 10
leftPad(100, 2) // 100
leftPad(1, 3) // 001
leftPad(1, 8) // 00000001
In all modern browsers you can use
numberStr.padStart(2, "0");
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
function zeroPad(numberStr) {
return numberStr.padStart(2, "0");
}
var numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
numbers.forEach(
function(num) {
var numString = num.toString();
var paddedNum = zeroPad(numString);
console.log(paddedNum);
}
);
It seems you might have a string, instead of a number. use this:
var num = document.getElementById('input').value,
replacement = num.replace(/^(\d)$/, '0$1');
document.getElementById('input').value = replacement;
Here's an example: http://jsfiddle.net/xtgFp/
Here is a very simple solution that worked well for me.
First declare a variable to hold your number.
var number;
Now convert the number to a string and hold it in another variable;
var numberStr = number.toString();
Now you can test the length of this string , if it is less than desired you can append a 'zero' at the beginning.
if(numberStr.length < 2){
number = '0' + number;
}
Now use the number as desired
console.log(number);
I know this is an ancient post, but I wanted to provide a more flexible and OO solution option.
I've extrapolated the accepted answer a bit and extended javascript's Number
object to allow for adjustable zero padding:
Number.prototype.zeroPad = function(digits) {
var loop = digits;
var zeros = "";
while (loop) {
zeros += "0";
loop--;
}
return (this.toString().length > digits) ?
this.toString() : (zeros + this).slice(-digits);
}
var v = 5;
console.log(v.zeroPad(2)); // returns "05"
console.log(v.zeroPad(4)); // returns "0005"
Edit: Add code to prevent cutting off numbers longer than your requested digits.
NOTE: This is obsolete in all but IE. Use padStart()
instead.
There is not a built-in number formatter for JavaScript, but there are some libraries that accomplish this:
You can use the padStart
method:
more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
function n(num, len = 2) {
return `${num}`.padStart(len, '0');
}
console.log(n( 9)); //print "09"
console.log(n(10)); //print "10"
console.log(n(999)); //print "999"
console.log(n(999,6));//print "000999"
Updated for ES6 Arrow Functions (Supported in almost all modern browsers, see CanIUse)
const formatNumber = n => ("0" + n).slice(-2);
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#test').keypress(allowOnlyTwoPositiveDigts);
});
function allowOnlyTwoPositiveDigts(e){
var test = /^[\-]?[0-9]{1,2}?$/
return test.test(this.value+String.fromCharCode(e.which))
}
</script>
</head>
<body>
<input id="test" type="text" />
</body>
</html>
I built a pretty simple format function that I call whenever I need a simple date formatted. It deals with formatting single digits to double digits when they're less than 10. It kicks out a date formatted as Sat Sep 29 2018 - 00:05:44
This function is used as part of a utils variable so it's called as:
let timestamp = utils._dateFormatter('your date string');
var utils = {
_dateFormatter: function(dateString) {
let d = new Date(dateString);
let hours = d.getHours();
let minutes = d.getMinutes();
let seconds = d.getSeconds();
d = d.toDateString();
if (hours < 10) {
hours = '0' + hours;
}
if (minutes < 10) {
minutes = '0' + minutes;
}
if (seconds < 10) {
seconds = '0' + seconds;
}
let formattedDate = d + ' - ' + hours + ':' + minutes + ':' + seconds;
return formattedDate;
}
}
str.padStart(2, '0'));
See this answer: stackoverflow.com/a/66344598/648298 – Eran W