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);
Related
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.
When I do:
var answer=a+b
if a was 4 and b was 5 then my answer comes out as 45. How can i get them to numerically add. I can do all other operations(*/-) but not add. Ik its a stupid question but im new and trying to lean
var prea,a,answer2,answer4,answer3,b,preb,answer1;
prea=document.getElementById("form1") ;
a=prea.elements["first"].value;
preb=document.getElementById("form1") ;
b=preb.elements["second"].value;
answer1=a*b;
answer2=a-b;
answer3=a/b;
answer4=a+b;
document.write("Multiplication:"+answer1);
document.write("<br>");
document.write("Subtraction:"+answer2);
document.write("<br>");
document.write("Division:"+answer3);
document.write("<br>");
document.write("Add:"+answer4);
Use Number(a) + Number(b) to calculate them. If you using strings instead of numbers, you just concatinate them instead of adding.
https://www.w3schools.com/jsref/jsref_number.asp
The variables are being declared as strings. You need to type cast them as an integer value to properly add them using parseInt(string).
The reason all the other operators work is because they will try to type juggle. However, javascript uses + for both numerical addition and string concatenation. So you have to explicitly use integer types if you want the result to be a summation.
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());
This question already has answers here:
Why won't my inputs value sum?
(5 answers)
Closed 8 years ago.
i am trying to make a maths engine with JavaScript and HTML.
Here is (http://i.stack.imgur.com/NCEa4.jpg)
The alert from the js alert() function works but the output from it is wrong:
'HTMLObject'
Value of the input field is always a string. So when you use + operator with two strings it concatenates them. If you want to add two numbers you need first to convert strings to numbers. There are multiple ways to do it, for example:
var plus = parseInt(one) + parseInt(two);
Or you can use Number(one), or another unary + operator: +one + +two, but this might look confusing.
Use 'parseInt()' function to convert those values to integers first and then add the values.
make your variable plus like this:
var plus = parseInt(one) + parseInt(two);
You need to enclose your function code in curly braces { & }.
So Use:
function Maths(){
var one=document.getElementById("fid").value;
var two=document.getElementById("sid").value;
var plus=Math.parseInt(one)+Math.parseInt(two);
alert(plus);
}
Also use parseInt() to make data type conversion to convert to int in JavaScript.
Hope it'll help you. Cheers :)!!
Will be better if you use second argument in parseInt for be sure that value will be in decimal system.
function Maths() {
var one = document.getElementById("fid").value,
two = document.getElementById("sid").value,
plus = Math.parseInt(one, 10) + Math.parseInt(two, 10);
alert(plus);
}
Sorry if this is a stupid question. I am a newbie to programming...
I have 3 values from a text input. I want 2 of these values to be stored into separate arrays for later access. finally I want to display a sum of these 3 values in my document.
What am I doing wrong?
Here is my code:
<script>
function displayCurrentBalance() {
var initialBalance = parseFloat(document.getElementById("initialBalance").value);
var inAmounts=[0];
var outAmounts = [0];
inAmounts.push(document.getElementById("amountIn").value);
outAmounts.push(document.getElementById("amountOut").value);
var sumIn = (inAmounts.reduce(function(a, b) {
return a + b[1];
}, 0));
var sumOut = (outAmounts.reduce(function(c, d) {
return c + d[1];
}, 0));
var result = initialBalance + sumIn - sumOut;
document.write(result);
};
displayCurrentBalance();
</script>
document.write(result); will overwrite your document before you even have a chance to enter the values. Make it display a value in another input box, or alert(result).
You should probably attach displayCurrentBalance to an onclick handler of some button, like <button onclick="displayCurrentBalance()">Calculate</button>.
document.getElementById("amountIn").value and similar calls will give you a string. You should use parseFloat or parseInt to convert it to an integer or a float.
You are likely calling the function before the elements are available in the page. Otherwise the script should be below the elements in the page.
You main problem is how you are using reduce. The values returned from the inputs are strings, so convert them to numbers before trying to add them (otherwise you will be concatenating strings, not adding numbers). You should probably validate the values too.
Also, reduce is called with the values of the members of the array, not the array itself (which is the 4th parameter provided to the callback, not the second), so:
var sumIn = (inAmounts.reduce(function(a, b) {
return +a + +b;
}, 0));
Modify the other call to reduce similarly. I don't think you need to provide an initial value since you initialise the array as [0]. Alternatively, keep the initial value in the call and initialise the array as [] (i.e. an empty array).
Rather than using document.write to display the result, better to write it as the value of a read–only input element so you can update it with subsequent calls as the user modifies the values in the other inputs.