Converting Text Field to Numerical Value (Getting NaN) - javascript

I have this bit of code, it's supposed to take the value from one field, and calculate the value from it based on a certain percentage (in this case 60%).
I created a hidden field to store the value in the html, but when I run the calculation and check it in Firebug it gets a NaN value. Can anyone tell me what I can do to produce the number I need?
(Apply_RequestedAmtX_r != 0 & Apply_RequestedAdvanceAmtY_r !=0){
var AmtX= ($('#Apply_RequestedAdvanceAmtX_r').val());
var AmtY= ($("#Apply_AmtYAfterSplit_r").val());
var MaxAMT = parseInt((AmtY*60)/100);
$('#mna').val(MaxAMT

val returns a string. Now, the way you're using those variables, they'll get automagically converted to numbers (although it's best practice to parse them yourself).
One or the other of your values has a character in it that prevents the value from being automatically converted to a number; and then since that's NaN, any math involving it will be NaN. If you examine AmtX and AmyY in Firebug before using them, you should see whatever that character is.
Again, parsing isn't the actual problem here, but you're using parseInt in exactly the wrong place (unless you were trying to use it to truncate the fractional portion of the number, in which case there are better choices). Here are the right places:
var AmtX= parseInt($('#Apply_RequestedAdvanceAmtX_r').val(), 10);
var AmtY= parseInt($("#Apply_AmtYAfterSplit_r").val(), 10);
var MaxAMT = (AmtY*60)/100;
MaxAMT will likely have a fractional portion. If you want MaxAMT to be an integer, then:
var MaxAMT = Math.round((AmtY*60)/100);
// or
var MaxAMT = Math.floor(AmtY*60)/100);
// or
var MaxAMT = Math.ceil(AmtY*60)/100);
...depending on your needs.

Related

Correctly format a whole number to a 2 decimal places output in JS but put 0 in front [duplicate]

I have a script which returns a price for a product. However, the price may or may not include trailing zeros, so sometimes I might have 258.22 and other times I might have 258.2. In the latter case, I need to add the trailing zero. How would I go about doing this?
You can use javascript's toFixed method (source), you don't need jQuery. Example:
var number = 258.2;
var rounded = number.toFixed(2); // rounded = 258.20
Edit: Electric Toolbox link has succumbed to linkrot and blocks the Wayback Machine so there is no working URL for the source.
Javascript has a function - toFixed - that should do what you want ... no JQuery needed.
var n = 258.2;
n.toFixed (2); // returns 258.20
I don't think jQuery itself has any string padding functions (which is what you're looking for). It's trivial to do, though:
function pad(value, width, padchar) {
while (value.length < width) {
value += padchar;
}
return value;
}
Edit The above is great for strings, but for your specific numeric situation, rosscj2533's answer is the better way to go.

How do I convert a phone number in NodeJS to a standard format?

I want to standardise phone numbers into a +<countrycode><areacode><number> format. Problem is the input might be:
+972-54-5123456
+972545123456
972545123456
+972 (54) 5123456
00972545123456
0545123456 // especially problematic, as I have to assume it's an Israeli number
I would like to normalize all to either 972545123456 or +972545123456 format, whatever the input is. So it will probably be:
normalizeNumber('0545123456',default_country="IL")
Use Google's libphonenumber. Here's the npm:
https://www.npmjs.com/package/google-libphonenumber
Taken from that page, a usage example:
// Require `PhoneNumberFormat`.
var PNF = require('google-libphonenumber').PhoneNumberFormat;
// Get an instance of `PhoneNumberUtil`.
var phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance();
// Parse number with country code.
var phoneNumber = phoneUtil.parse('202-456-1414', 'US');
// Print number in the international format.
console.log(phoneUtil.format(phoneNumber, PNF.INTERNATIONAL));
// => +1 202-456-1414
Pretty simple, just code it up:
function normalizeNumber(input, default_country) {
return String(input)
.replace(/[^+0-9]/g, '') // remove non-number (and +) characters
.replace(/^00/, '+') // replace leading 00 with +
.replace(/^0/, getCountryCode(default_country)) // replace leading 0 with default code
}
If you want you can split the statement up and add some checks, such as whether the final result starts with a + and/or is of some expected length.
The following modules could be used as a source for getCountryCode:
country-data
country-calling-codes

wanted to add two floating number which gets concatenated as string

i want to add two float number with fixed two decimal but its converted to string and get concatenated.I know its simple question but actually i'm in hurry
var a=parseFloat("15.24869").toFixed(2)
var b=parseFloat("15.24869").toFixed(2)
Update when i enter input as
var a=parseFloat("7,191");
var b=parseFloat("359.55");
c=(a+b).toFixed(2)
O/P:NAN
why so?
The .toFixed() method returns a string. Call it after you've performed the addition, not before.
var a=parseFloat("15.24869");
var b=parseFloat("15.24869");
var c=(a+b).toFixed(2);
After that, c will be a string too, so you'll want to be careful.
As to your updated additional question, the output is not NaN; it's 366.55. The expression parseFloat("7,191") gives the value 7 because the , won't be recognized as part of the numeric value.
Just add parenthesys to parse float the whole result string
var a=parseFloat((15.24869).toFixed(2));
var b=parseFloat((15.24869).toFixed(2));
c=a+b
doing c = a + b adds the two answers together. You might just want to turn them into a string then concatenate them.
var a=parseFloat("15.24869").toFixed(2)
var b=parseFloat("15.24869").toFixed(2)
var c = (a.toString() + b.toString());

Angular giving error "Model is not of type `number`" when typeof === number

As a work around to not being able to filter inputs without directives I've attempted the following:
On the input ngChange detects a change and runs a function. The input has type="number"
<input type="number"
ng-model="ctrl.met.mass"
ng-change="ctrl.met.update.mass()">
The function updates some other fields, then formats them. In this example I want it to display two decimal points with toFixed(2). This is done with variable = variable.toFixed(2)
ctrl.met.cost = ctrl.met.mass * ctrl.met.price;
ctrl.imp.mass = ctrl.met.mass * 0.0353;
ctrl.imp.cost = ctrl.imp.mass * ctrl.imp.price;
console.log(typeof ctrl.met.mass); // number
ctrl.met.mass = ctrl.met.mass.toFixed(2);
console.log(typeof ctrl.met.mass); //string
But the number isn't formatting as well as I'm receiving this error; note the number at the end of the URL is 29.00, being the desired result. If the number is 12.34 that would be in place of 29.00.
Error: ngModel:numfmt
Model is not of type `number`
But when I run typeof ctrl.met.mass at any point, or any other variable I'm working with, it's telling me it is in fact a number except after .toFixed() has interacted with it.
The same error has occurred with the Angular Number Filter (after injecting), parseInt(), parseFloat(), and toPrecision() (to a precision of 4, to ensure two decimal places for a two digit number).
ctrl.met.mass = $filter("number")(ctrl.met.mass, 2);
ctrl.met.mass = $filter("number")(parseInt/Float/Precision(ctrl.met.mass), 2);
ctrl.met.mass = ctrl.met.mass.toInt/Float
ctrl.met.mass = ctrl.met.mass.Precision(4);
I'm thinking I won't be able to do so this way, and will need to use a directive. Before I try that though, why is this happening and can it be worked around?
edit: It seems what I'm trying is impossible. Upon setting ctrl.met.mass to what was, without a doubt, a number with two decimal places it rejected it in preference for an integer. If anyone knows why this is the case, please share.
The returned value from the toFixed method is a string. So you need to convert it to float in your controller:
var fixed = ctrl.met.mass.toFixed(2);
ctrl.met.mass = parseFloat(fixed);
you can make a stringToNumber directive to parse string to number, the perfect example of this is shown at below link :
https://docs.angularjs.org/error/ngModel/numfmt

jQuery: Content of html element is interpreted as a string, not an integer

When somebody is liking a comment on my website, a "1" is added at the right of the number where the amount of likes are shown, but when they click dislike, it does correct math.
For example:
14 + 1 = 141
14 - 1 = 13
jQuery
var elem = $('.like_button'), //Like button
num = $('.num_likes'), //Get the element: number of likes
oldnum = num.html(); //Number of likes
if(elem.html() == "Like") {
elem.html("Dislike");
num.html(oldnum+1); //Adds one like after liking it
} else {
elem.html("Like");
num.html(oldnum-1); //Deletes one like after disliking it
}
I really wonder why disliking works but liking not.
Why does javascript interpret the value of the num element as a string, even though it is a number? Any tips for me?
Because JavaScript interprets num.html() as text. The + sign for string in javascript means concatenation, but - doesn't mean that so in that case javascript realizes you want to do numeric calculation. That's why it works with -
You should cast oldnum to an integer with parseInt().
You need to cast oldnum to a number:
if(elem.html() == "Like") {
elem.html("Dislike");
num.html(Number(oldnum)+1); //Adds one like after liking it
} else {
elem.html("Like");
num.html(Number(oldnum)-1); //Deletes one like after disliking it
}
Alternatively, +oldnum does the same thing as Number(oldnum).
Javascript is interpreting the text on your page as a string. This is because that's what text on a page normally is. Take for example:
<span id="berliner">I am a jelly donut.</span>
<script LANGUAGE="Javascript">
document.getElementById("berliner").innerHTML;
// it only makes sense that this be a string, right?
</script>
Now, in JS, you use the + sign for two things: adding numbers, or putting one string after another.
var addingnumbers = 1+1;
// adding numbers, what you want
var a = "I am";
var b = " a jelly donut";
var addingstrings = a+b;
// adding strings, which you don't want.
As such, the html was interpreted as a string like it normally should be, but in this case shouldn't be. And adding the string to the other string just appended it to the end, rather than doing math. There is an easy solution: convert the innerHTML to a number by multiplying it by 1. Multiplying can't be done to a string, so JS will change it to number form, prepping it to be added to something else.
var oldnum = num.html()*1; // done! The multiplying has changed it to a number.
And if you ever do want to change it back to a string, you can do the reverse with the toString() function.
var aNumberToStartOutWith = 3;
var aStringToEndOffWith = aNumberToStartOutWith.toString();

Categories