number formatting javascript - javascript

I have a problem with formatting my numbers. I found a script on this forum that I will show below this text. It does work with the comma, but when I add a number like 10000000.00, it will become 10000000,00, but if I add a number like 10333333.00, it will become: 10 33 33 33,00, and that is not what I want. I want to have my number format like this: 10 333 333,00 .
I have been searching for a long time for a solution on this. I tried to change the regex, but i am not that good yet with regex, so i hope someone can help me with this problem.
this is the script:
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;
}

var tests =
[
3141,
314159,
31415926,
10000000.001,
10333333.002,
42121.1415926535
],
res,
i;
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;
}
for (i = 0; i < tests.length; i++)
{
document.write(addCommas(tests[i]) + '<br>');
}
The \d+{3} was odd and rejected by JSLint (and not working on Firefox).
Code tested on JSFiddle.

Related

Force two decimals on this localisation function for large numbers [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have the following function that automatically adds the commas to an American numerical expression which is some way of localisation. I need a minor change to this function.
if I have 160 * 54.08 = 8.652,8 as input to the function what can I do to show the output as 8.652,80 with two decimal places? Right now the function outputs as 8.652.8
function Numberformat(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;
}
function Numberformat(nStr) {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? ',' + x[1] : ',0';//if there is no decimal
//force ",00"
x2 = x2.length < 3? x2 + "0" : x2;//if length of decimal + delimiter is
//less than 3 add an extra 0
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + '.' + '$2');
}
return x1 + x2;
}
document.body.innerHTML = Numberformat(160 * 54.08);//8.652,80
document.body.innerHTML += '<br>' + Numberformat(8560);//8.560,00
document.body.innerHTML += '<br>' + Numberformat(8560.0);//8.560,00
document.body.innerHTML += '<br>' + Numberformat(8560.1);//8.560,10
document.body.innerHTML += '<br>' + Numberformat(8560.01);//8.560,01
document.body.innerHTML += '<br>' + Numberformat(8560.009);//8.560,009
Check this answer:https://stackoverflow.com/a/149099/3025534
You can use:
var profits=2489.8237
profits.toFixed(3) //returns 2489.824 (round up)
profits.toFixed(2) //returns 2489.82
profits.toFixed(7) //returns 2489.8237000 (padding)
Then you can add the sign of '$'.
If you require ',' for thousand you can use:
Number.prototype.formatMoney = function(c, d, t){
var n = this,
c = isNaN(c = Math.abs(c)) ? 2 : c,
d = d == undefined ? "." : d,
t = t == undefined ? "," : t,
s = n < 0 ? "-" : "",
i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
And use it with:
(123456789.12345).formatMoney(2, '.', ',');
If you're always going to use '.' and ',', you can leave them off your method call, and the method will default them for you.
(123456789.12345).formatMoney(2);
If your culture has the two symbols flipped (i.e. Europeans), just paste over the following two lines in the formatMoney method:
d = d == undefined ? "," : d,
t = t == undefined ? "." : t,
I would do something like this
var n = '1.000,00';
if (wrongFormat(n)) {
n = n.replace(',', '#');
n = n.replace('.', ',');
n = n.replace('#', '.');
}
var val = 1*n;
//do something with val here

How to convert long number string value to numeric value using Javascript / jQuery

User is allowed to insert up to 25 value in textbox.
i.e. 1234567890123456789012345
On change event of textbox I need to convert that same into numeric value to perform numeric operations and then after need to display same entered value with thousand separator along with 2 decimal places.
I tried the following code:
Number($('#textbox1').val()).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",")
parseInt($('#textbox1').val(), 10).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",")
Both gives me following output
1.2,345,679,801,234,568e+21
expected output:-
1,234,567,890,123,456,789,012,345.00
Try using autoNumeric js. Find it here
something like this work for you? I found it on the internet...
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 + '.00';
}
for the numeric point of view, still i could not get any solution at JavaScript, so I have posted the value to server side and get JSon result.
But for the display purpose I have did finally :
function ChangeAmountFormat(target) {
var $this = $(target);
var num = $this.val().replace(/,/g, '').replace(/(\s)/g, '');
var decimalPointDeleted = '';
if (lastValue.length > 0 && lastValue.indexOf('.') > 0 && num.indexOf('.') < 0) {
decimalPointDeleted = 'y';
}
if (num.indexOf('.') >= 0) {
var numSplitValues = num.split('.');
num = numSplitValues[0].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
num += (num.length > 0 ? ('.' + numSplitValues[1]) : '');
}
else {
if (decimalPointDeleted == 'y' && num.toString().substring((num.length - 2), num.length) == '00') {
var tempNum = num.toString().substring(0, (num.length - 2));
num = tempNum + '.' + num.toString().substring((num.length - 2), num.length);
}
else {
num = num + (num.length > 0 ? '.00' : '');
}
num = num.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
$this.val(num);
}
here, some more things also handles. Kindly ignore.

convert decimal to string without removing 0 "zero(s)"?

nStr = 12.00;
alert(typeof(nStr));// getting number
x = nStr.split('.');
// Other than string Split function Through an error,
nStr = 12.00;
nStr += '';
alert(typeof(nStr));// getting string
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
alert(x1+x2);
//Expected Output is 12.00
I got the temp output coding ( its not optimized coding)
nStr += '';
x = nStr.split('.');
x1 = x[0];
x[1]= (x[1].length == 1) ? '.' + x[1] + '0' : '.' + x[1];
x2 = x.length > 1 ? x[1] : '.00';
alert(x1+x2); // 12.00
12.00 is 12 you can't change that fact.
Looks like what you are after is the toFixed() method of JavaScript:
nStr = 12;
alert(nStr.toFixed(2));
This will alert "12.00" as you want. The number passed to the method determines how many digits after the decimal point will be displayed.
Worth mentioning is that the toFixed method will also round numbers, for example if in the above example nStr will be 12.5283 it will show 12.53 in the alert.
Instead of writing
nStr = 12.00;
u can write something like this
nStr = "12.00";

JavaScript how to display numbers

I computed a number in JavaScript function.
Example:
var price = 1000;
var commission = 200;
var total = price + commission
After I added these two I want to show the total as 1,200 (put , in between 3 digits).
From: http://www.mredkj.com/javascript/numberFormat.html
This functionality is not built into JavaScript, so custom code needs to be used. The following is one way of adding commas to a number, and returning a string.
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;
}
function addCommas(price) {
var x = (parseFloat((isNaN(price) ? 0 : price)).toFixed(2)+'').split('.');
var x3 = x[0].substr(-3);
for(var i=x[0].length-3; i>0; i=i-3)
x3 = x[0].substr((i < 3 ? 0 : (i-3)), (i < 3 ? i : 3))+","+x3;
return x3 + (x.length > 1 ? '.' + x[1] : '');
}
When you do just want an integer value instead of an float with 2 digits, just change the last line to
return x3;
often i use toLocaleString depents abit on what im doing (some parts of the world use comma insted of dot and visa for delimiting
var total = (price + commission).toLocaleString()

Getting a NaN on click event

I have a script that simply adds fields 2 & 3, but because I have formatted the numbers as currency ($x,xxx.xx) field1 returns NaN. Is it is possible to strip the $ symbol from the number before doing the calculation? I assume the comma and period won't cause the same issue.
onclick="document.getElementById('field1').value = (Math.round((parseFloat(document.getElementById('field2').value,2)*100))/100 + Math.round((parseFloat(document.getElementById('field3').value,2)*100))/100).toFixed(2);"
prior to clicking the calculate button, I am formatting the numbers being added onblur="forA();" (as soon as user leaves fields) with:
function forA() {
document.getElementById('fieldY').value = "$" + addCommas1(document.getElementById('fieldZ').value);
}
function addCommas1(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;
}
Just remove all non dot / digits before doing calculations
var currency = "$2,358.88";
var number = Number(currency.replace(/[^0-9.]+/g,""));

Categories

Resources