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

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

Related

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.

number formatting 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.

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

Javascript Number formatting min/max decimals

I'm trying to create a function that can format a number with the minimum decimal places of 2 and a maximum of 4. So basically if I pass in 354545.33 I would get back 354,545.33 and if I pass in 54433.6559943 I would get back 54,433.6559.
function numberFormat(num){
num = num+"";
if (num.length > 0){
num = num.toString().replace(/\$|\,/g,'');
num = Math.floor(num * 10000) / 10000;
num += '';
x = num.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;
}
else{
return num;
}
}
New 2016 solution
value.toLocaleString('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 4
});
Do not forget to include polyfill.
compat table
API docs
Old 2011 solution
To format a part, after decimal point you can use this:
value.toFixed(4).replace(/0{0,2}$/, "");
And for part before decimal point: How to write this JS function in best(smartest) way?
You're doing it wrong.
54433.6559943.toFixed(4) will round to 4 places. You then have to trim off up to two trailing zeroes.

Categories

Resources