I use one small code js to add comma to value:
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
I have problem when try to add comma to big values like sextillion values.
Eg.
addCommas(1000000) //return correct "1,000,000"
but if use big values like this
addCommas(50949024266983356472874) // return wrong "5.094902426698335e+22"
What or where I do wrong?
Your input might already be a float. Numbers larger than 2^32 tend to be like this. Make sure your input is a string and your function will run fine.
JavaScript doesn't have int and float types. Instead it just has a Number type and it will decide on it's own when to use which.
When you do
nStr += '';
You're asking javascript to first convert your number to a string. That's when it decides to write it as "5.094902426698335e+22". The problem isn't in the rest of your algorithm.
The conversion is described here in ecmascript
If your number is stored in a string the following function will achieve what you are asking for.
function addCommas( txtNum ) {
var parts = txtNum.split(".");
parts[0] = parts[0].reverse().replace(/(\d{3})/g, "$1,").reverse();
return parts.join(".");
}
String.prototype.reverse = function () {
return this.split("").reverse().join("");
}
addCommas( "-50000000000000000000000000000000000000000.0000" );
// => -50,000,000,000,000,000,000,000,000,000,000,000,000,000.0000
Related
I am working on an internship project that, although it's not focused on performance, I would want to be as fast (and lean) as possible. So far, I have one working version (with a bug) and one concept of the aforementioned function:
V1 (BUG: Can't handle numbers with dots and commas.)
function addCommas(nStr) {
if (isNaN(nStr)) {
throw new Error(`${nStr} is NaN`);
}
// Alternative: isNaN(nStr) ? throw new Error(`${nStr} is NaN`) : nStr += ``;
nStr += ``;
// If the input is of the form 'xxxx.yyy', split it into x1 = 'xxxx'
// and x2 = '.yyy'.
let x = nStr.split(`.`);
let x1 = x[0];
let x2 = x.length > 1 ? `.` + x[1] : ``;
let rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
// x1 takes the form 'x,xxx' - no matter how long the number,
// this is where the commas are added after every three digits.
x1 = x1.replace(rgx, `$1` + `,` + `$2`);
}
return x1 + x2;
}
V2 Concept (looks slower but no known bugs)
function addCommas(nStr) {
if (isNaN(nStr)) {
throw new Error(`${nStr} is NaN`);
}
nStr += ``;
// Remove any potential dots and commas.
nStr = nStr.replace(`.`, ``);
nStr = nStr.replace(`,`, ``);
// Split the number into an array of digits using String.prototype.split().
// Iterate digits. After every three, add a comma.
// Transform back into a string.
return nStr;
}
Check out the function toLocaleString:
const b = 5120312039;
console.log(b.toLocaleString()); //"5,120,312,039"
Try this
var str = "123456789";
var result = [...str].map((d, i) => i % 3 == 0 && i > 0 ? ','+d : d).join('').trim();
console.log(result);
When i print a floating point like 0.0000001 in JavaScript it gives me
1e-7
how can i avoid that and instead print it "normally" ?
You can use this:
var x = 0.00000001;
var toPrint = x.toFixed(7);
This sets toPrint to a string representation of x with 7 digits to the right of the decimal point. To use this, you need to know how many digits of precision you need. You will also need to trim off any trailing 0 digits if you don't want them (say, if x was 0.04).
function noExponent(n){
var data= String(n).split(/[eE]/);
if(data.length== 1) return data[0];
var z= '', sign= +n<0? '-':'',
str= data[0].replace('.', ''),
mag= Number(data[1])+ 1;
if(mag<0){
z= sign + '0.';
while(mag++) z += '0';
return z + str.replace(/^\-/,'');
}
mag -= str.length;
while(mag--) z += '0';
return str + z;
}
I've got a simple solution that appears to be working.
var rx = /^([\d.]+?)e-(\d+)$/;
var floatToString = function(flt) {
var details, num, cnt, fStr = flt.toString();
if (rx.test(fStr)) {
details = rx.exec(fStr);
num = details[1];
cnt = parseInt(details[2], 10);
cnt += (num.replace(/\./g, "").length - 1); // Adjust for longer numbers
return flt.toFixed(cnt);
}
return fStr;
};
floatToString(0.0000001); // returns "0.0000001"
EDIT Updated it to use the toFixed (didn't think about it).
EDIT 2 Updated it so it will display numbers 0.0000000123 properly instead of chopping off and showing "0.00000001".
Having an issue with commas and values.
I have a value that keeps changing all the time from checkboxes, sliding from jQuery ui slider and keyup functions. I want to add commas to the total that is being changed each time rather than building it into each function. If I have to build it into each function, I am not opposed to that either though. The end value just needs to have commas in it.
Here's a fiddle: http://jsfiddle.net/ZSeHU/
Any thoughts here?
Replace $("#increasedRevenueValue").val(value) with setIncRevenueValue(value)
Inside, use
$("#increasedRevenueValue").val('$'+addCommas(value));
where addCommas is the following function:
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
This is the source: http://www.mredkj.com/javascript/nfbasic.html
I have a script that takes a big number and counts up. The script converts the number to a string so that it can be formatted with commas, but I also need to add a decimal place before the last two digits. I know that this line handles the commas:
if ((i+1) % 3 == 0 && (amount.length-1) !== i)output = ',' + output;
Is there a similar line of code I can add that accomplishes adding a decimal point?
Yes, if you always want the decimal before the last two:
function numberIt(str) {
//number before the decimal point
num = str.substring(0,str.length-3);
//number after the decimal point
dec = str.substring(str.length-2,str.length-1)
//connect both parts while comma-ing the first half
output = commaFunc(num) + "." + dec;
return output;
}
When commaFunc() is the function you described that adds commas.
EDIT
After much hard work, the full correct code:
http://jsfiddle.net/nayish/TT8BH/21/
Are you sure want the decimal to be just before the last two digits? That way 1234 would become 12.34 and not 1234.00, I'm assuming you want the second one, in that case you should use JavaScript's built in method .toFixed()
Note I didn't write the format_number function, I took it from the website below and modified it a bit.
http://www.mredkj.com/javascript/nfbasic2.html
http://www.mredkj.com/javascript/nfbasic.html
// example 1
var num = 10;
var output = num.toFixed(2); // output = 10.00
// example 2, if you want commas aswell
function format_number(nStr)
{
nStr = nStr.toFixed(2);
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
var num = 1234;
var output = format_number(num); // output = 1,234.00
function addCommas(nStr) {
nStr += '';
var x = nStr.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
P = addCommas(P);
$("#monthly_result").html(P.toFixed(2));
I left out the P calculations, so keep in mind it is outputting a number in the thousands with decimals.
I got the function from stack and it works well adding commas to numbers in the thousands. However when I tried to limit the value to 2 decimal places it doesnt output anything.
Thanks
my answer is pretty simple but would be what your looking for:
http://phpjs.org/functions/number_format:481
Example:
$("#monthly_result").html(number_format('1234.56', 2));
toFixed is not available for strings (which your addCommas function returns).
simple solution would be to convert the number to a float by using parseFloat and then cut the decimal places using toFixed and convert back to string to proceed with your function.
for a fixed number of decimal places, something along the lines of:
function addCommas(num) {
var num = parseFloat(num).toFixed(2)+'',
rgx = /(\d+)(\d{3}[\d,]*\.\d{2})/;
while (rgx.test(num)) {
num = num.replace(rgx, '$1' + ',' + '$2');
}
return num;
}
In this case, addCommas(61423.34512); would return "61,423.35". I'd recommend using the number_format function posted by Robert for some extra formatting options, though.