JavaScript is concatenating instead of adding [duplicate] - javascript

This question already has answers here:
Javascript concatenating numbers, not adding up
(3 answers)
Closed 5 years ago.
I am using these in my code:
alert(mult); //1.114
alert(profit); //10
price = (mult * profit) + profit;
alert(price); //11.14 should be 21.14
I also tried price = ((mult*profit) + profit); but got the same result. Instead of doing (1.114*10) + 10; it is doing 1.114*10=11.14. It is not adding the additional 10 at the end.

It works fine for me like this. It doesn't seem that concatenation is an issue, because otherwise the value would be '11.1410'.
var mult = 1.114;
var profit = 10;
var price = (mult*profit) + profit;
alert(price);//11.14 should be 21.14
If the profit variable (or both variables) is a string, the result would be "11.1410".
var mult = 1.114;
var profit = '10';
var price = (mult*profit) + profit;
alert(price);//11.1410
The result seems unaffected if just the mult value is a string.
var mult = '1.114';
var profit = 10;
var price = (mult*profit) + profit;
alert(price);//21.14

The variables are probably strings, use parseFloat to convert them to numbers :
mult = parseFloat(mult);
profit = parseFloat(profit);
price = (mult*profit) + profit

The problem is probably that either mult or profit are of type string and not of type number. This can be fixed by explicitly casting.
You can determine the type of your variables in your browser console (i.e. dev tools) with the typeof keyword like this:
typeof foo
If either of your variables are of type string you can convert them to number with parseFloat:
mult = parseFloat(mult);

I just ran this is in the chrome js console F12 key.
var mult = 1.114, profit = 10;
console.log('mult=', mult);//1.114
console.log('profit=', profit);//10
price = (mult*profit) + profit;
console.log('price=', price);//11.14 should be 21.14
And got these results
mult= 1.114
profit= 10
price= 21.14

Related

Javascript output showing NAN values?

Javascript output showing Nan when i enter large values like 6564646464,6516654,555 input values?
$("#calculate").click(function () {
var need_hotel = $("#hotel_need").val();
var event_day = $("#event_day").val();
var result_1 = parseFloat(need_hotel * event_day);
var result_2 = result_1 * 165;
var result_3 = result_2 * 0.03;
$("#ans1").text(result_1.toFixed(2));
$("#ans2").text(result_2.toFixed(2));
$("#ans3").text('£' + (result_3).toLocaleString('en'));
$("#results_container").show();
});
Javascript has iffy support for such large numbers
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER
You might wanna try BigInt
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt

Why is my number coming up as 0? [duplicate]

This question already has answers here:
How do I get the value of text input field using JavaScript?
(16 answers)
Closed 6 years ago.
I am trying to make a calculator that calculates the amount of calories that have been burned in a certain amount of time, but whenever I run it, I get 0 as the output. I have tried setting the calorieCountOut variable to an arbitrary number, and then it works fine, but every time I run it with this code here, I get 0. Here is my code:
const AGECONST = 0.2017;
const WEIGHTCONST = 0.09036;
const HRCONST = 0.6309;
const SUBTRACTCONST = 55.0969;
const TIMECONST = 4.184;
//var gender = document.getElementById("gender").innerHTML;
var gender = "male";
var weight = document.getElementById("weight");
var age = document.getElementById("age");
var time = document.getElementById("time");
var hr = 140;//dummy number
function calculate(){
if (gender = "male"){
var calorieCount = ((age * AGECONST) - (weight * WEIGHTCONST) + (hr * HRCONST) - SUBTRACTCONST) * time / TIMECONST;
}
//else if (gender = "female"){
//}
var calorieCountOut = calorieCount.toString();
document.getElementById("output").innerHTML = calorieCountOut;
}
Try getElementById('myId').value for the value inside the control instead of the control itself as an object.
Right now you assign a html object to a variable, but what you want (i assume) is the number stored in that html object.

how to convert big decimal value to decimal in javascript

var zx =1800;
I have some value in big decimal value i need to convert it as decimal in javascript.
I have tried using zx.doubleValue() method but i m getting error as "Uncaught ReferenceError: Double is not defined" In browser console.
var bigdecimal = require("bigdecimal");
var i = new bigdecimal.BigInteger("1234567890abcdefghijklmn", 24);
console.log("i is " + i);
// Output: i is 60509751690538858612029415201127
var d = new bigdecimal.BigDecimal(i);
var x = new bigdecimal.BigDecimal("123456.123456789012345678901234567890");
console.log("d * x = " + d.multiply(x));
// Output: d * x = 7470299375046812977089832214047022056.555930270554343863089286012030
var two = new bigdecimal.BigDecimal('2');
console.log("Average = " + d.add(x).divide(two));
// Output: Average = 30254875845269429306014707662291.561728394506172839450617283945
var down = bigdecimal.RoundingMode.DOWN();
console.log("d / x (25 decimal places) = " + d.divide(x, 25, DOWN));
// Output: d / x (25 decimal places) = 490131635404200348624039911.8662623025579331926181155
As I understood you receiving big decimal from backend. The problem with JavaScript is that native Number type is limited in precision, thus your big decimal will be truncated.
You can use one of libraries, for example, big number:
https://www.npmjs.com/package/big-numbers
This will allow you to convert received from backend numbers to big number:
const bigNumberValue = numbers.of([received from backend value]);
After it is done, you can perform any required operation: add, multiply, etc. Check JavaScript tutorial here:
http://bignumbers.tech/tutorials/java-script

Add percent to numbers

How can I add percent to a sum? I have tried var sum = 3.25 + '3.4%'; but it didn't work. I'm just getting 0.00 as an answer.
To "add a percent to a number" means "multiply the number by (1 + pct)":
var sum = 3.25;
sum = sum * (1 + 0.034);
You could equivalently skip the 1 (that's just the way I think about it) and add:
var sum = 3.25;
sum += sum * 0.034;
So if you're starting off with a string representation of a percentage, you can use parseFloat() to make it a number:
var pct = "3.4%"; // or from an <input> field or whatever
pct = parseFloat(pct) / 100;
The parseFloat() function conveniently ignores trailing non-numeric stuff like the "%" sign. Usually that's kind-of a problem, but in this case it saves the step of sanitizing the string.
The simplest method is to use arithmetic operators.
var sum = 3.25
sum += sum *= 0.034;
< 3.3605
String concatenation and number adding using the same + symbol. You need to use () around the numbers.
var sum = (3.25+3.4)+"%";
let's assume that you want to add x percent to the current number :
const percentage = 14.5; let number = 100 const numberPlusPercentage = number + number / 100 * percentage
console.log('result = 'numberPlusPercentage.toFixed(2))
result = 114.5

JavaScript issue in IE when adding numbers

I have a simple form, with 5 textboxes and 3 answers (also textboxes). The form calculates a result for the user with number inputs. My problem is my calculation does not work in IE, but works fine in both Chrome and Firefox.
What's wrong?
Here is my function:
function addNumbers()
{
var val1 = Number(document.getElementById("value1").value);
var val2 = Number(document.getElementById("value2").value);
var val3 = Number(document.getElementById("value3").value);
var val4 = Number(document.getElementById("value4").value);
var val5 = Number(document.getElementById("value5").value);
var val6 = '100';
var ansD1 = document.getElementById("answer1");
ansD1.value = Number((val1 * val2) * (val4 / val6));
var ansD2 = document.getElementById("answer2");
ansD2.value = Number((val1 * val3) * (val5 / val6));
var ansD3 = document.getElementById("answer3");
ansD3.value = Number (ansD1.value - ansD2.value);
}
Change this line:
var val6 = '100';
to this:
var val6 = 100;
You want all your values to be actual numbers (not strings) so you can do math on them.
Also, you don't need the Number() in these lines because the result of the numeric math is already a number. Plus the assignment to the answer fields is just going to convert the result to a string anyway:
ansD1.value = Number((val1 * val2)*(val4/val6));
They can just be this:
ansD1.value = (val1 * val2)*(val4/val6);
The modified code works fine in IE here: http://jsfiddle.net/jfriend00/5WFRA/.
Instead of Number use parseInt, otherwise they are treated as strings

Categories

Resources