This question already has answers here:
How to format a number with commas as thousands separators?
(50 answers)
Closed 8 years ago.
How can I take a JavaScript integer of arbitrary length, such as 1234567890, and format it as a string "1,234,567,890"?
You can use toLocaleString() for the format that you have asked.
var myNum = 1234567890;
var formattedNum = myNum.toLocaleString();
The best way is probably with a regular expression. From How to print a number with commas as thousands separators in JavaScript:
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
My solution:
var number = 1234567890;
var str = number + "";
var result = str.split('').map(function (a, i) {
if ((i - str.length) % 3 === 0 && i !== 0) {
return ',' + a;
} else {
return a;
}
}).join('');
See fiddle.
Related
This question already has answers here:
Split large string in n-size chunks in JavaScript
(23 answers)
Closed 5 months ago.
I am trying to solve a math problem where I take a number e.g. 45256598 % 2==0 and then split the number into separate two char digits like e.g. 45,25,65,98. Does anyone know how to split a number into individual two char digits?
I Have Already Achieved this C# code but this Method I am looking in JavaScript code :-
My C# code is:-
string str = "45256598";
int n = 2;
IEnumerable<string> numbers = Enumerable.Range(0, str.Length / n).Select(i => str.Substring(i * n, n));
You can do this by using match
like this:
const splittedNumbers = "45256598".match(/.{1,2}/g)
This will return array of:
['45','25','65','98']
If you would like to split in different length, just replace 2 with the length
const splittedNumbers = "45256598".match(/.{1,n}/g)
Hope this will help you!
<!DOCTYPE html>
<html>
<body>
<script>
const str = "45256598";
if((str * 1) % 2 === 0) {
const numArr = [];
for(let i = 0; i < str.length; i = i + 2) {
const twoDigit = str.charAt(i) + (str.charAt(i+1) ?? ''); // To handle odd digits number
numArr.push(twoDigit);
}
let result = numArr.join(',');
console.log(result);
}
</script>
</body>
</html>
This question already has answers here:
How to format numbers as currency strings
(67 answers)
Closed 6 years ago.
I have tried using Number(x).toLocaleString(), but this only gives me 10,000.
When I use parseFloat(row.profit).toFixed(2) it gives me 10000.00. I tried combining parseFloat(Number(row.profit)toLocaleString()).toFixed(2) But not give me the desired output which should be 10,000.00.
How can I achieve this?
You can use a quick hack by testing if . is present in your locale string or not :
function localeFormat(x) {
var num = Number(x).toLocaleString();
if (num.indexOf("/.") > 0) {
num += ".00";
}else{
var n = parseFloat(x).toFixed(2).toString();
num = Number(n).toLocaleString();
}
return num;
}
var strs = ["10000", "10000.45", "10000.45768"];
for(var i = 0; i < strs.length; i++){
console.log(strs[i] + " -> " + localeFormat(strs[i]));
}
This question already has an answer here:
Javascript Adding Two Decimal Places
(1 answer)
Closed 9 years ago.
I have a float,
var a = 324620.8
and I want it to look like this
a = 324620.80
This is my code so far,
var a_float = a;
var a_int = parseInt(a);
d = a_float - a_int;
if(d <= 0){
a = a_int+'.00';
}else{
if(d < 0 && d > 0.1){
a = a_int + d + '0';
}else{
a = a_float;
}
}
This would works for only one decimal digit.
I want it to work when I have 2 decimal digits.
.toFixed would not work in some browsers.
Answering the question in the title
How to find how many decimal digits in a float?
Compare position of '.' to length of float as a String.
var x = 1.2345,
x_str = x.toString(),
decimal_digits = x_str.length - x_str.lastIndexOf('.') - 1;
decimal_digits === x_str.length && (decimal_digits = 0); // case no decimal
decimal_digits; // 4
JSFIDDLE
Use toFixed("2");
var f = 1.3454545;
f.toFixed(2);
var decimal = 4.0;
var a = (decimal).toFixed(2);
console.log(a); // outputs 4.00
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
JavaScript equivalent to printf/string.format
How can I create a Zerofilled value using JavaScript?
I have a number in a variable:
var number = 5;
I need that number to be output as 05:
alert(number); // I want the alert to display 05, rather than 5.
How can I do this?
I could manually check the number and add a 0 to it as a string, but I was hoping there's a JS function that would do it?
There's no built-in JavaScript function to do this, but you can write your own fairly easily:
function pad(n) {
return (n < 10) ? ("0" + n) : n;
}
EDIT:
Meanwhile there is a native JS function that does that. See String#padStart
console.log(String(5).padStart(2, '0'));
Try this
function pad (str, max) {
return str.length < max ? pad("0" + str, max) : str;
}
alert(pad("5", 2));
Example
http://jsfiddle.net/
Or
var number = 5;
var i;
if (number < 10) {
alert("0"+number);
}
Example
http://jsfiddle.net/
This question already has answers here:
How can I pad a value with leading zeros?
(76 answers)
Closed 3 years ago.
Is there a way to prepend leading zeros to numbers so that it results in a string of fixed length? For example, 5 becomes "05" if I specify 2 places.
NOTE: Potentially outdated. ECMAScript 2017 includes String.prototype.padStart.
You'll have to convert the number to a string since numbers don't make sense with leading zeros. Something like this:
function pad(num, size) {
num = num.toString();
while (num.length < size) num = "0" + num;
return num;
}
Or, if you know you'd never be using more than X number of zeros, this might be better. This assumes you'd never want more than 10 digits.
function pad(num, size) {
var s = "000000000" + num;
return s.substr(s.length-size);
}
If you care about negative numbers you'll have to strip the - and read it.
UPDATE: Small one-liner function using the ES2017 String.prototype.padStart method:
const zeroPad = (num, places) => String(num).padStart(places, '0')
console.log(zeroPad(5, 2)); // "05"
console.log(zeroPad(5, 4)); // "0005"
console.log(zeroPad(5, 6)); // "000005"
console.log(zeroPad(1234, 2)); // "1234"
Another ES5 approach:
function zeroPad(num, places) {
var zero = places - num.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + num;
}
zeroPad(5, 2); // "05"
zeroPad(5, 4); // "0005"
zeroPad(5, 6); // "000005"
zeroPad(1234, 2); // "1234" :)
You could extend the Number object:
Number.prototype.pad = function(size) {
var s = String(this);
while (s.length < (size || 2)) {s = "0" + s;}
return s;
}
Examples:
(9).pad(); //returns "09"
(7).pad(3); //returns "007"
From https://gist.github.com/1180489
function pad(a, b){
return(1e15 + a + '').slice(-b);
}
With comments:
function pad(
a, // the number to convert
b // number of resulting characters
){
return (
1e15 + a + // combine with large number
"" // convert to string
).slice(-b) // cut leading "1"
}
function zfill(num, len) {return (Array(len).join("0") + num).slice(-len);}
Just for fun (I had some time to kill), a more sophisticated implementation which caches the zero-string:
pad.zeros = new Array(5).join('0');
function pad(num, len) {
var str = String(num),
diff = len - str.length;
if(diff <= 0) return str;
if(diff > pad.zeros.length)
pad.zeros = new Array(diff + 1).join('0');
return pad.zeros.substr(0, diff) + str;
}
If the padding count is large and the function is called often enough, it actually outperforms the other methods...