I wish to format a number so that it has "leading zeros" (thus string is always equal length). - While I could as backup do this manually I wish to use the best option. - As a standard format syntax (like pythons "{0:4d}".format(number)
) seems to be unavailable, the next best is to use the internationalization library?
I've tried doing this in a fiddle: https://jsfiddle.net/f4202ne3/1/
let fmt = new Intl.NumberFormat('en-US',
{minimumIntegerDigits: 4,
maximumFractionDigits: 0
});
m = 1;
n = 5001
console.log(m.toString(), fmt.format(m)) //"0001"
console.log(n.toString(), fmt.format(n)) ///"5000"
However this displays "5,000" and "0,001". How do I set the thousands separator to a value ( ''
)?
Simply set the useGrouping
option to false
let fmt = new Intl.NumberFormat('en-US', {
minimumIntegerDigits: 4,
maximumFractionDigits: 0,
useGrouping: false
});
You can use the .pad
string method ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart )
"1231".padStart(8,0)//00001231
"131".padStart(8,0)//00000131
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.