wanted to add two floating number which gets concatenated as string - javascript

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

Related

Multiply a number which has a comma with javascript

Im trying to multiply a value which contains a comma(lets keep this comma). I cant find anything that seem to work, as everything that I have tried returns as NaN.
var value = 2,55;
// value = 44.000,55 also possible
var amount = 117;
var total = value * amount;
alert(total);//returns NaN
var value = 2,55;
That is not 2.55; it is 2, a comma and then 55. If I put that into the console of the dev tools of a chromium based browser I get "Uncaught SyntaxError: Unexpected number".
Because it is not valid syntax, in a var expression commas are used to define multiple locals.
JavaScript number literals can only use a period as a decimal separator: while parsing functions (converting from strings at runtime) can supper internationalisation the source code does not.
If you are creating code dynamically, the code to create the code has to handle creating syntactically correct code:
var value = 2.55; // or 4000.55
Assuming you are trying to operate on monetary values, it would be better to get the value as a string and convert it to float then back to string if you want to keep the comma:
var value = "2,55";
var amount = 50123123123;
var total = parseFloat(a.replace(',', '')) + b;
total = total.toString().split("").reverse().join("").split('').reduce((a, e, i)=> a + e + (i % 3 === 2 ? ',' : ''), '');
total=total.split("").reverse().join("");

Text box not showing decimal values jQuery

In my jQuery program, I have 3 textboxes. One for net weight, one for rate and the last readonly text box for amount. The amount textbox calculates the product of the rate and the netweight textboxes and displays the result.
function amtcal(id)
{
var ab="#a"+id;
var ntwt=parseInt($(ab).val(),10);
var a="#"+id;
var rval=parseInt($(a).val(),10);
var product=rval*ntwt;
var abc="#aa"+id;
$(abc).val(product);
}
Check out the working example at jsFiddle.
The program is working but the error that it is causing is that it ignores the decimal values. If I input the following :-Nt wt = 5.5 | Rate = 5.2, the output is given as 25.
Don't use parseInt to convert text to numbers unless the result you want really is an integer. parseFloat or Number will do the job here. ;)
Just remove parseint and let it be rval=$(a).val();
You're using parseInt which will remove all decimal values (making it an int), use parseFloat instead which will keep it (thus making it a float).
Use this JS:
function amtcal(id)
{
var ab="#a"+id;
var ntwt=parseFloat($(ab).val());
var a="#"+id;
var rval=parseFloat($(a).val());
var product=rval*ntwt;
var abc="#aa"+id;
$(abc).val(parseFloat(product).toFixed(2));
}
Here .toFixed() is used to show 2 digits after decimal point.
I have update jQuery code and updated in jsfiddle.
Here is updated jQuery.
function amtcal(id){
var ab="#a"+id;
var ntwt=$(ab).val();
var a="#"+id;
var rval=$(a).val();
var product=rval*ntwt;
var abc="#aa"+id;
$(abc).val(product);
}

Converting Text Field to Numerical Value (Getting NaN)

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.

Combining retrieved values with javascript and jquery [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I Convert a String into an Integer in JavaScript?
I have a select element that contains options for products. What I want to achieve is when they pick an option the price on the page automatically adjusts. I have figured out how to retrieve those values but when I combine them it just puts two numbers together instead of actually adding them.
For example instead of outputting 60 when I have 50 + 10 it outputs 5010.
My code:
$('.product_options').change(function(){
var base_price = $('#base_price').html();
var add_price = $(this).find("option:selected").data('price');
var new_price = base_price+add_price;
console.log(new_price);
$('.current_price').html(base_price+add_price);
});
Is there a way I can convert them both to integers so the operation actually goes through?
Thanks in advance!
Use parseInt
$('.product_options').change(function(){
var base_price = parseInt($('#base_price').html(), 10); // 10 as second argument will make sure that base is 10.
var add_price = parseInt($(this).find("option:selected").data('price'), 10);
var new_price = base_price+add_price;
console.log(new_price);
$('.current_price').html(base_price+add_price);
});
Try:
var base_price = +$('#base_price').html();
var add_price = +$(this).find("option:selected").data('price');
See the mighty: Mozilla's Arithmetic Operators Reference - Unary Negation
Any values you pull out of the DOM are going to be strings, and need converting into number types before you can do mathematical operations with them.
parseInt( ... ) is a built in javascript function that converts a string into an integer, if the string consists of digits only.
If you need a decimal number, you can use parseFlaot.
var new_price = parseInt(base_price)+parseInt(add_price);
// new_price is now set to the sum of `base_price` and `add_price`
Use parseFloat or parseInt
$('.product_options').change(function(){
var base_price = $('#base_price').html();
var add_price = $(this).find("option:selected").data('price');
var new_price = parseFloat(base_price) + parseFloat(add_price);
console.log(new_price);
$('.current_price').html(base_price+add_price);
});
Yes there is.
intval = parseInt(string)
is what you're looking for.

jQuery + parseDouble problem

I have an AJAX-request that returns a json object containing a few values with two decimals each, but since it's json these values are strings when returned. What I need to do is to perform addition on these values. Just a simple a+b = c, but they concatenate instead becoming ab.
I was hoping I could use parseDouble in jQuery just like I can use parseInt but apparantly I can't. At least not what I've found. So the question remains, is there any way I can add these two string values into a double or float value? Or should I just calculate this on the server side and send the already additioned value back to the browser and jQuery.
Example:
This is what happens
5.60 + 2.20 = 5.602.20
This is what should happen
5.60 + 2.20 = 7.80
Thankful for answers.
Just use parseFloat():
var c = parseFloat(a) + parseFloat(b);

Categories