Calculation for comma number gives NaN value - javascript

I tried to multiply 2 input where user need to key in the number but the output gives me NaN value.
The input number btw have comma separator. I tried to implement the method from the link below and the comma separator is working. It just that when I multiply them it gives me NaN value.
Can jQuery add commas while user typing numbers?
Can anybody help me with this. Really appreciate your help.
Javascript
$('.textInput').on('change keyup', function() {
// skip for arrow keys
if(event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/(\d)(?=(\d{3})+$)/g, '$1,');
;
});
product_total_price=0;
var product_price= Number($('#id_Product-0-price').val());
var product_quantity= Number($('#id_Product-0-quantity').val());
product_total_price= product_price * product_quantity;
$('#id_Product-0-total_price').val(product_total_price);
});

The problem here is that you have modified your inputs to show commas, which is totally fine, BUT you didn't remove the commas before casting/converting them to Number.
A quick test of converting a Number from string "1,234" will give you a NaN result. See screenshot:
Solution:
Remove Comma
Then cast to Number
Then compute product_total_price
To remove all commas, simpy use:
yourString.replace(/,/g, '')
Hope this helps!

Related

Function not calculating values of formatted numbers

I built a calculator that takes user input (1 text field, 2 select dropdowns) and then displays the output below if the required conditions are met. I also wanted to have the text input field display thousand separators (commas) dynamically as the user types in a number, which I achieved using this:
$('#orderAmt').keyup(function(event) {
// skip for arrow keys
if (event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
});
});
Now, as expected, the calculator function doesn't recognize any of these values because they have been converted to strings. I assume that the next step is to use something like parseInt, so I added this line at the end of the .keyup function:
var converted = parseInt($('#orderAmt'), 10);
But I'm lost on what to do next, because the actual calculator function is written in vanilla JS and here I am trying to store the user's value in a new jQuery variable. Is there a better approach that I should be taking with this?
Here's my JSFiddle - https://jsfiddle.net/bkroger7/yk13wzcc/
If anyone can point me in the right direction it would be greatly appreciated.
BTW - I've tried the infamous, non-jQuery addCommas function as seen here but it won't work for me - only jQuery-based solutions have been working so far.
your problem is you are adding commas to the input field and then taking it as is...
so when you use $('#orderAmt').val() after you add commas you will get 3,000 instead of 3000
what you need to do is just remove the commas...
here is a working fork
https://jsfiddle.net/Lw9cvzn0/1/
notice: var orderAmount = $('#orderAmt').val().replace(new RegExp(','), '');
You're missing the call to .val() to get the field's value. And then you have to remove the commas before you parse it.
var converted = parseInt($('#orderAmt').val().replace(/,/g, ''), 10);

How can I remove all decimals from a JavaScript variable?

How can I remove all decimals from a number? I want to get the number as specified below. I need to remove decimal points only. I am not getting the logic for it.
If number x= 1.1.6;
then I want result as 116
and when x=0.0.6;
then I want result as 6.
Since 1.1.6 is not a valid numerical value in JavaScript, I assume that you're starting with a string. You can get the result as an integer value with:
parseInt(number.replace(/\./g, ''))
If desired, you can then turn that back into a string with no leading zeroes with:
'' + parseInt(number.replace(/\./g, ''))
try this. replace all the . using replace method and convert to integer
document.write(parseInt("1.1.6".replace(/\./g, '')))
document.write('<br>')
document.write(parseInt("0.0.6".replace(/\./g, '')))

How to round a number up and add numeric punctuation

I've got the following pen: http://codepen.io/anon/pen/LVLzvR
I cant quite figure out how to round the number up so you don't break the punctuation. I need to round the number up as I don't want to see a value like 33,333.,333
//ADDS PUNCTUATION EVERY THREE CHARACTERS
$('input.numericpunctuation').keyup(function(event){
var oNum= $(this).val(); // USE THIS NUMBER FOR CALCULATION
var num = oNum.replace(/,/gi, "").split("").reverse().join("");
var num2 = RemoveRougeChar(num.replace(/(.{3})/g,"$1,").split("").reverse().join(""));
console.log(num2);
console.log(oNum);
// the following line has been simplified. Revision history contains original.
$(this).val(num2);
});
function RemoveRougeChar(convertString){
if(convertString.substring(0,1) == ","){
return convertString.substring(1, convertString.length)
}
return convertString;
}
Example input event:
If I input 5555, is expect to see (and do see) 5,555. However if I add 5555.55 I get 5,555,.55. Ideally id like to round the number up removing the decimal.
The problem isn't just with decimals, you will get the wrong formatting also by entering non digits, e.g., clicking King Kong will result in Kin,g K,ong. So, what you probably want is to filter out non-digits, which can be done by changing the line var oNum= $(this).val(); to:
var oNum= $(this).val().match(/\d/g).join('');
The value inside the match function is a RegEx object - if you never used it before then congratulations!

Formatting an American Number format to a Integer

I know I am asking a dull question but at this point of time it is not dull to me.
I have a number say
$123,245,123 in my text box on executing the onBlur function this value is when rounded or done mathematical it is showing as Nan
How will I format this number to a integer.
var value = '$123,245,123'
value = value.Replace?(/[$,]/g, '')
please help in correcting my script to avoid NaN
This should work:
var value = '$123,245,123'
value = parseFloat(value.replace(/[$,]/g, ''));
try Number('$123,245,123'.replace(/[$,]/g, '')).
That's: replace (lowercase r), without ?
Using Number-conversion, values like '$123,245,123.23' are also converted (to float)
Instead of Number, a simple + is equivalent: +('$123,245,123'.replace(/[$,]/g, ''))
If you need a check for NaN, use something like:
var dollarvalue = +('$123,245,123'.replace(/[$,]/g, '')) || 0;
If you only want to keep the dollar value (no cents, integer), use
(+('$123,245,123.43'.replace(/[$,]/g, ''))).toFixed(0);
If you want to round the dollar value, use
Math.round(+('$123,245,123.43'.replace(/[$,]/g, '')));

How to validate for Values "0" or "00" or "000" for textfield which has the regex and some accepted values

var myregex = /^[0-9][0-9]{0,3}$|^[0-9][0-9]{0,3}[\.][0-9]$/;
if(!myregex.test($('#txt1').val()) || $('#txt1').val()=="0"){
alert("Please Enter Correct value");
}
Now My mandatory things are it should
follow Regex
we should not able to enter the value "0" or "00" or "000"
So my above if() raises an alert if the user enter a "0" and if we enter "00" or "000" or "0000" it doesnot catch it .But if we enter "00000" it catches it due to regex. How can i handle for 2,3,4 zeros .Now Here I can put a regex which doesnot accept zeros such as this one "/^[^0].*$/" but My textfield should Accepts this values as right (0.2,0.3,0.4) .so i cannot use this regex.
Avoid regex, it's a nightmare to get exactly right, and to maintain in the future. Instead, use built-in JS string parsing functionality:
var val = parseFloat($('#txt1').val());
if (isNaN(val) || (val === 0))
{
alert("Please Enter Correct value");
}
/^[1-9]\d{0,3}(?:\.\d)?$|^0\.[1-9]$/
The first alternative matches any number from 1.0 to 9999.9. The first digit has to be at least 1, which eliminates leading zeroes. The fraction part is optional ((?:\.\d)?), so it also matches integers from 1 to 9999. The second alternative handles the special cases of 0.1 through 0.9.
It looks like your regular expression requires 0 through 9999, or 0.0 through 9999.9, but you do not want to accept a 0 alone, or a series of zeros.
If that's the case, I'd say use something similar to ken's answer and process it as a float, then check that the float is above 0 and below 9999.9:
var val = parseFloat($("#txt1").val());
if(isNan(val) || val <= 0 || val > 9999.9) {
alert("Please enter a value between 0 and 9999.9");
}
If you need to use your regex and just add a check that the string doesn't consist entirely of zeroes, you can add a negative lookahead expression: (?!0+$) and enclose the alternation in a non-capturing group:
/^(?!0+$)(?:[0-9][0-9]{0,3}|[0-9][0-9]{0,3}[\.][0-9])$/
No need for Regex or any of that, quite simple.
if(('#txt1').val() < 0.1 ){
alert("Please Enter Correct value");
}
There you go, problem solved

Categories

Resources