Function not calculating values of formatted numbers - javascript

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

Related

Calculation for comma number gives NaN value

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!

If statement returning NaN

Am totaling several form fields where users put in hours of the day. However, some users would like to put an "X" if they were not present that day. So I tried several different if statements to try to get the calculation to recognize "X" as a zero when running the calculation but still show an X in the form field. I went as far as creating a hidden form field and default its value to zero and that is the last thing I tried.
Here is my formula (please keep in mind, I will have to use this for each day of the week but I just was playing around with the first one)
var v1 += getField("mon1_str."+row).value;
if(v1 == "X") event.value = "defaultvalue";
else event.value = "";
The first line of script gets my value no problem. Its the second line and third line where i am not having any luck. It should be noted that no errors are coming up in the console window. "defaultvalue" is the name of my hidden form field to grab a value from.
The + tries to convert the string to a number. But 'x' can't be converted to a number, so it results in NaN.
console.log(+'X');
Try saving the plain value, checking if it's 'X', and then converting it to a number later.

Validating numeric input while formatting numeric input

In an asp.net-mvc project using C#.
I use a function to format larger numbers with commas such as 1,000,000, thanks to this post:
function numberWithCommas(str) {
return str.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
The issue is, I have the inputs locked down to accept only numbers with a min value of zero.
<input type="number" min="0" class="myclass" value="#somevalue" />
This poses a problem using the JS, as it needs only number input. Which brings me to a question like this How to make HTML input tag only accept numerical values?, which also offers a JS solution.
I'm wondering if anyone has developed an elegant way to format numeric input display, while validating numeric input, is there are any other options available here? It doesn't have to purely be a JS solution.
You can't use the numeric input, because, well, JavaScript doesn't consider formatted number to be a number.
The option is to use the non-numeric input but filter out any "problematic" chars.
In the following example, I'm also handling the dot separator in case you need to accept fractions.
As the text box is being edited, it also has to preserve the cursor position. I've achieved it there with the help of Updating an input's value without losing cursor position.
function format(inp){
var start = inp.selectionStart, // get the selection start
end = inp.selectionEnd; // and end, as per the linked post
var s1=inp.value.split(",").length-1; //count the commas before edit
inp.value=numberWithCommas(inp.value.replace(/,|[^\d.]/g,''));
var s2=inp.value.split(",").length-s1-1; //count the commas after edit so as to know where to place the cursor, as the position changes, if there are new commas or some commas have been removed
inp.setSelectionRange(start+s2, end+s2); // set the selection start and end, as per the linked post
}
function numberWithCommas(str) {
var a=str.split('.');
var p=/\B(?=(\d{3})+(?!\d))/g;
if(a.length>1)
return a[0].toString().replace(p, ",")+"."+a[1];
else
return str.toString().replace(p, ",");
}
<input onkeyup="format(this)">
I have the answer of your first question.
You can disable all keys rather than only numbers keys.
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 43 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;
return true;
}
I also created working demo on jsfiddle
The program flow:
Getting the input via an on change event and calling the other functions, showing passing the data through a Ajax POST.
$('.Amount').on("change", function (e) {
var myInput = $(e.target);
var input = this.value;
// Remove any non digits (including commas) to pass value to controller.
var Amount = validateInput(input);
// Format the string to have commas every three digits 1,000,000 for display.
var val = numberWithCommas(Amount);
$(myInput).val(val);
$.ajax({
type: 'POST',
dataType: "json",
url: somesUrl + '/' + somethingelse,
data: JSON.parse('{"Amount": "' + Amount + '"}'), // Amount is a nice format here and will not throw an error.
// TODO etc
});
});
Remove any non numbers and give a value of zero if no numbers are inputted.
var validateInput = function (input) {
input = input.toString().replace(/[^0-9]/g, "");
/* Remove leading zeros. */
input = input.replace(/^0+/, '');
if (input == "")
input = 0;
return input;
}
Format the input with commas 1,000,000,000.
function numberWithCommas(str) {
return str.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
So even if the user types input with commas e.g. 1,734,567 it will work and if they misplace where they put a commas e.g. 17,35,555 it will still validate.
See working fiddle.
I actually worked out a nice solution while trying to meet project deadlines and in part this was solved by this answer by nicael.
This solution does not check the input as it is being typed, but after it is finished, I chose the change event, as opposed to the input event, as it calls the function once and (similar to a submit event) than validates the input in one call. Removing any commas and non digits; solving the issue of formatting with commas, by removing them for the ajax call, then reformatting it with commas for the display. There is a check to remove leading zeros.
If all the input is garbage I replace this value with zero to prevent an error passing to the controller with null data (just a design choice, could display a toast message instead).

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!

JavaScript: Retrieve negative floating point number from string of mutiple sums

I have a simple app that allows me to caculate the total amount invoiced and deposited in a route. However I want to allow the user to input multiple values in a single input field; e.g:
500+50+36.5-45.2-10.
I have written a function that will retrieve this input and then split this string into elements of an array at the + sign and immediately parse the values to numbers and then add them and return the total the user inputs into each individual field. This is all well as long as the user does no use any sign other than +.
I have searched the use of regexp:
regular expression in javascript for negative floating point number result stored in array
Javascript Regular expression to allow negative double value?
but none of the results seem to work.
How could I make my code retrieve the values so that the negative values get passed into the array as negative values?
Here is a snippet of my Js code:
For the full code, visit my fiddle.
totalInvoiced: function () {
var a = A.invoiced.value;
var value1Arr = [];
value1Arr = a.split("+").map(parseFloat);
var value1 = 0;
value1Arr.forEach(function (value) {
value1 += value;
});
I really like PhistucK's solution, but here an alternative with regex:
value1Arr = a.split(/(?=\+|\-)/);
This will split it, but keeps the delimiter, so the result will be:
["500", "+50", "+36.5", "-45.2", "-10"]
A bit dirty, but maybe a.replace(/-/g, "+-").split("+"), this way, you add a plus before every minus, since the negative numbers just basically lack an operator.
You can use this pattern that splits on + sign or before - sign:
var str = '500+50+36.5-45.2-10';
console.log(str.split(/\+|(?=-)/));

Categories

Resources