Put commas in input value - javascript

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

Related

What's the fastes way to take big numbers (e.g. 1900234) and put commas after every three digits?

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);

js add comma at Sextillion values

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

Putting commas in a number in JavaScript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Place commas in Javascript integers
I have a variable containing a number in JavaScript and I want to display it with commas in all the right places. So, for 222222 I need 222,222 and for 1000333 I need 1,000,333. What's the simplest way to do this?
Try this:
function addGrouping(val, grouper) {
val += '';
x = val.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + grouper + '$2');
}
return x1 + x2;
}
addGrouping(1231.897243, ",")
// 1,231.897243
Example fiddle

Add a decimal to a string

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

having problems adding commas to number while limiting it to only 2 decimal places

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.

Categories

Resources