Consider:
<html>
<body>
<input Id="1"></input>
<input Id="2"></input>
<button Id="3"onclick="add()">Add</button>
<script>
function add()
{
var num1 = document.getElementById("1").value;
var val1 = parseInt(num1);
var num2 = document.getElementById("2").value
var val2 = parseInt(num2);
var val3 = val1 + val2;
var x = +num1 + +num2;
alert(val3);
</script>
</body>
</html>
I want to add two numbers in JavaScript. But when I am providing '11111111111111111' to a textbox, parseInt is converting it into 11111111111111112 instead of 11111111111111111. Why is it doing this?
I have tried all techniques. I first converted var to string and parsed it into int then added, used different radix with parseInt, but I still get nothing.
I also noted that when I am providing 16 1's to it, it's working fine, but with 17 1's it's doing this.
JavaScript numbers are IEEE 754 doubles which have 15-17 significant digits precision.
In your case the 11111111111111111 number has 17 digits which causes the observed issues.
Related
I am facing an issue with rounding decimals in JavaScript using toFixed.
const num1 = (100.555).toFixed(2) // "100.56"
const num2 = (10.555).toFixed(2) // "10.55"
Can any one explain why this behavior happens? Why first example round the decimals to 56 while the second one turn it to 55?
Update:
If i add 4 decimals then rounding is differnt.
const num3 = (10.5555).toFixed(2) // "10.56"
This should fix your problem
// its a rounding bug it can be compenstated by representing numbers exactly in decimal notation.
Number.prototype.toFixedDown = function(digits) {
var re = new RegExp("(\\d+\\.\\d{" + digits + "})(\\d)"),
m = this.toString().match(re);
return m ? parseFloat(m[1]) : this.valueOf();
};
const num1 = 100.555.toFixedDown(2)
const num2 = (10.555).toFixedDown(2)
alert(num1+ ' ' + num2);
It is because of precision problem in floating numbers....You can find libraries for precision calculation for npm like
"npm install bigdecimal"
Link here:
BigDecimal Reference
var x = new bigdecimal.BigDecimal("123456.123456789012345678901234567890");
and you can use it like that it should be fine.....
Hope this somewhat clarifies your problem....peace
I have a javascript program there use bitwise OR operator to get a OR result from two numbers:
Sample code:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to return the number of characters in the string "Hello World!".</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "80400001";
var a = parseInt(str, 16);
var str = "12345678";
var b = parseInt(str, 16);
n = b|a;
document.getElementById("demo").innerHTML = n;
}
</script>
</body>
</html>
But the result is always negative, that is not my expected value.
Result:
-1837869447
Eventhough I try to OR a number with zero, the result is still negative...
It doesn't happen in Java, but in Javascript.
Can you tell how can I get the same result as that in Java?
You can use this change signed int to unsigned int:
n>>>0
var str = "80400001";
var a = parseInt(str, 16);
var str = "12345678";
var b = parseInt(str, 16);
n = b | a;
console.log((n>>>0).toString(16))
see: Bitwise operations on 32-bit unsigned ints?
I believe the problem is that unlike e.g. Java and Python JavaScript does not have a 64 bit integer type. When you use the bitwise operators in JS, the number is truncated to 32 bits, the operation is performed, then it is cast back to an IEEE 754 float. 0x80400001 is 2,151,677,953 which is bigger than 2,147,483,647 (max signed 32 bit int) and you're losing the significant bits which is giving the odd result.
There are arbitrary size integer libraries one can use.
Also checkout cyrilluce's answer for a way to do it without an external lib.
The reason is because number in javascript is 64bit floating point, but bitwise operator work on 32bit int, in your example variable a is larger than 31^2, so when you apply a bitwise operator it changed to negative. One way I can think of around it is to use unsigned right shift to push off the signed bit, and add back the bit pushed off.
var str = "80400001";
var a = parseInt(str, 16);
var str = "12345678";
var b = parseInt(str, 16);
n = parseInt(((a|b) >>> 1).toString(2) + (a%2|b%2), 2);
console.log(n)
This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 5 months ago.
I created a simple program that make the sum of two numbers BUT..
the program is concatenating instead, This is so confusing!
Can anyone help?
function calculate() {
var numberOne = document.querySelector(".first").value;
var numberTwo = document.querySelector(".second").value;
var sum = numberOne + numberTwo;
document.querySelector(".result").innerHTML = "The sum of the two numbers is : " + sum;
}
<!doctype html>
<html>
<body>
<p>Calculate sum of two numbers !</p>
Enter 1rst Number:<br>
<input type="number" class="first" placeholder=""><br><br> Enter 2nd Number:<br>
<input type="number" class="second" placeholder=""><br><br>
<input type="button" onclick="calculate()" value="calculate">
<p class="result"></p>
</body>
</html>
Here value gives you a string, hence the concatenation. Try parsing it as an Number instead:
var sum = parseInt(numberOne) + parseInt(numberTwo);
See the demo fiddle.
Javascript takes dom elements as string only by default. To make mathematical calculation, you need to typecast it to integer/float or convert to number.
parseInt(number) = number, truncates after decimal value
parseFloat(number) = number with decimal values
Number(number) = number with or without decimal
Your numberOne and numberTwo are strings, so you get concatenated strings when use + sign with two string.
Parse first to numbers then sum them. You can use parseInt() and parseFloat() functions for it.
var numberOne = '7';
var numberTwo = '8';
var sum = numberOne + numberTwo;
console.log(sum);
sum = parseFloat(numberOne) + parseFloat(numberTwo);
console.log(sum);
Use parseInt() for this, Check snippet below
function calculate() {
var numberOne = document.querySelector(".first").value;
var numberTwo = document.querySelector(".second").value;
var sum = parseInt(numberOne) + parseInt(numberTwo);
document.querySelector(".result").innerHTML = "The sum of the two numbers is : " + sum;
}
<p>Calculate sum of two numbers !</p>
Enter 1rst Number:<br>
<input type="number" class="first" placeholder=""><br><br>
Enter 2nd Number:<br>
<input type="number" class="second" placeholder=""><br><br>
<input type="button" onclick="calculate()" value="calculate">
<p class="result"></p>
Example , you can use this:
var numberOne:number = +document.querySelector(".first").value;
var numberTwo:number = +document.querySelector(".second").value;
var sum = numberOne + numberTwo;
You should use + Angular typeScript
It's just because value returns with string. So sum operation ends with concatenation.
you need to convert both those values.
user below code
var sum = parseFloat(numberOne) + parseFloat(numberTwo);
Who are using javascript in salesforce make sure
var a= 8 ;
var b =8 ;
var c = a+b;
This will give u result output = 88;
It is will just concatenate. If you want to add those two:
You should write logic as :
var a = 8;
var b = 8
var c = parseInt(a)+ parseInt(b);
This will give you the desired result of 16 , The same is the case with multiplication.
Hope this helps.
I want to have 2 decimals in a number.
I tried using :
var number = (123).toFixed(2);
but it returns it in a string format. I want them to be numbers.
Also I tried using:
var number= parseFloat((123).toFixed(2));
but this removes the decimals if it is 0.
I want to show the numbers as decimals with fixed 2 decimals, also convert those numbers to toLocaleString("bn-IN-u-nu-latn")
For example:
number = 123456
output : 1,23,456.00
That's impossible. A number won't display trailing zeros past the decimal point. Only a string will.
For example, observe this output:
document.write(0.00); // output as a number, is 0
document.write("<br>");
document.write("0.00"); // output as a string, is 0.00
If you want a number to be rounded to two decimal places, but also have trailing zeros when needed, you must convert to a string before you output, which means (123).toFixed(2) is all you need.
Edit: To round the number, but also use a locale format. Use .toLocaleString() like such:
(0.00).toLocaleString("bn-IN-u-nu-latn", {
minimumFractionDigits:2,
maximumFractionDigits:2
});
Try :
var number = +parseFloat(Math.round(123 * 100) / 100).toFixed(2);
You can try this ..
Html
Value: <input type="text" id="myText" value="">
Javascript
<script>
num = 125;
num=num+1;
var R = num.toFixed(2); // returns 126.00
document.getElementById("myText").value = R;
</script>
Please see below screen......
I need to format numbers to two decimal digits in javascript. In order to do this I am using toFixed method which is working properly.
But in cases, where numbers don't have any decimal digits, it should not show decimal point
e.g. 10.00 should be 10 only and not 10.00.
.toFixed() converts the result to String,
so you need to convert it back to Number:
parseFloat( num.toFixed(2) )
or by simply using the Unary +
+num.toFixed(2)
both will give the following:
// 15.00 ---> 15
// 15.20 ---> 15.2
If you only want to get rid of the .00 case, than you can go for String manipulation using .replace()
num.toFixed(2).replace('.00', '');
Note: the above will convert your Number to String.
As an alternative to make this change global(if you need, of course), try this:
var num1 = 10.1;
var num2 = 10;
var tofixed = Number.prototype.toFixed;
Number.prototype.toFixed = function(precision)
{
var num = this.valueOf();
if (num % 1 === 0)
{
num = Number(num + ".0");
}
return tofixed.call(num, precision);
}
console.log(num1.toFixed(2));
console.log(num2.toFixed(2));
Fiddle. This is a mix of this and this post.