Comparing floating-point to integers in Javascript - javascript

So I ran across a small piece of code that looks like this
Math.random() * 5 | 0 and was confused by what it did.
after some inspecting, it seems like the comparison turns the decimal into an integer. is that right? and so the piece of code is another way is saying give me a random number between 0 and 4. Can anyone explain why that is?

1) Math.random() function always return decimal value and will be less than one. Ex - 0.2131313
random()
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
2) Math.random()*5 will always be less than 5. (maxvalue - 4.99999).
3) The bitwise operator '|' will truncate the decimal values.
Edit : Paul is correct. '|' does more than just truncate.
But in this case Math.random()*5|0 - It truncates the decimal and returns the integar.

Related

is there a difference between these two snippets of code and if yes what is it?

function addBinary(a,b) {
let sum= a+b
if (sum<0){
sum=0xffffffff+sum+1
}
return parseInt(sum).toString(2)
}
and especially the logic of how 0xffffffff has been used to achieve same result
function decimalToBinary(decimal){
return (decimal >>> 0).toString(2);
}
function addBinary(a,b) {
return decimalToBinary(a+b);
}
The >>> operator always interprets the given number as an unsigned 32 bit number. When the second operand is 0, nothing changes to that and the result is unsigned.
So for instance, -1 in binary is 0xffffffff in signed 32-bit, where the most significant bit (at the left) is the sign bit. But because exceptionally the >>> does not interpret that as a sign bit, it actually is seen as a positive number, i.e. 0xffffffff. Compared to the original -1 that is 0x100000000 more! This is always the difference for negative inputs. For -2 you'll get 0xfffffffe, for -3 you'll get 0xfffffffd, ...etc.
The first function emulates this. If sum is negative, we must do something, as the other function (using >>>) will never return a negative number.
The idea is to add that 0x100000000 difference. In fact, the author of this function was prudent, and evidently didn't want to work with numbers that exceed the 32 bit range, so 0x100000000 was off the board (it uses 33 bits). But one can split the job into parts. We can add one less (0xffffffff) to the sum, and then add the remaining 1. This is just a theoretical game though. In JavaScript there is no problem in adding 0x100000000, so they could just as well have done that. In other languages however, those that use 32 bit numbers, it would be necessary to first add 0xffffffff and only then 1.

Why round value is different?

I know if I round up -1.5, it's -2.
so I tried to do with C# it returns -2 correctly.
Console.WriteLine(Math.Round(-1.5, 0));
also I tried to do with Excel, it also returns -2.
=Round(-1.5,0)
but when I do with javascript, it returns -1.
Math.round(-1.5)
why this values are different?
and how can I get -2 instead of -1 when I do this with javascript?
Math.round(Math.abs(-1.5));
your value is negative that's why it gets -1. Just get the absolute value and then round it and multiply it to -1 to get -2.
yes round in javascript works as you said. One solution is convert your negative number to positive then use Math.round. At last you should convert your number to negative number.
function myFunction() {
num = -1.5;
document.getElementById("demo").innerHTML = Math.round(num);
if(num < 0)
document.getElementById("demo").innerHTML = -1 * Math.round(Math.abs(num));
}
That's just how they made it. It is acknowledged that it is different than most languages.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
If the fractional portion of the argument is greater than 0.5, the argument is rounded to the integer with the next higher absolute value. If it is less than 0.5, the argument is rounded to the integer with the lower absolute value. If the fractional portion is exactly 0.5, the argument is rounded to the next integer in the direction of +∞. Note that this differs from many languages' round() functions, which often round this case to the next integer away from zero, instead giving a different result in the case of negative numbers with a fractional part of exactly 0.5.

remove leading 0 before decimal point and return as a number- javascript

Problem
I need to return a number in the format of .66 (from an entered value which includes the leading zero, e.g. 0.66)
It must be returned as an integer with the decimal point as the first character.
what method in JavaScript can help me do this?
What have I tried?
I've tried converting it toString() and back to parseInt() but including the decimal point makes it return NaN.
I've tried adding various radix (10, 16) to my parseInt() - also unsuccessful
Sample Code
const value = 0.66;
if(value < 1) {
let str = value.toString().replace(/^0+/, '');
// correctly gets '.66'
return parseInt(str)
}
//result NaN
Expectations
I expect an output of the value with the leading 0 removed
e.g. 0.45 --> .45 or 0.879 --> .879
Current Observations
Output is NaN
I tried a quick solution, you may try to do this:
let a = 0.45;
// split on decimal, at index 1 you will find the number after decimal
let b = a.toString().split('.')[1];
Issue #1:
0.66 is not an Integer. An Integer is a whole number, this is a floating-point number.
Issue #2:
You cannot have a number in JavaScript that starts with a decimal point.
Even if you change your parseInt to be parseFloat, it will still return 0.66 as a result.
What you're asking just isn't possible, if you want a number to start with a decimal point then it has to be a string.

JavaScript Math.round: Doesnt round object to 1 decimal

I have objects in array:
x[{a=2.99, b=5.11}{a=4.99, b=2.11}]
And I want it to display 1 decimal with Math round, as I use Math.round(x[0].a*10)/10; it displays 3, while it works fine if I use just numbers as Math.round(2.99*10)/10.
Why is that?
please try the below code
x[0].a.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0]
you can round off to 1 by changing regex patter from {0, 2} to {0, 1}
Thiss might work -- Math.floor() and toFixed(1) are the keys here... rounding will cause the original input to change to the nearest integer.
function roundToTenth(inputVal) {
return Math.floor(inputVal * 10) * 0.1;
}
console.log(roundToTenth(2.99).toFixed(1));
Division is slower than multiplication is generally - and definitely using Regular Expression Matching is going to be slower than multiplication is....
All I'm doing in the code above is saying "Take the number times 10 and then turn it into a straight Integer with no Decimals,
so
2.99 * 10 = 29.9 which then becomes 29
finally, since I use the operation * 0.1 it becomes a float like 2.900000004 and I use toFixed(1) to strip out all those pesky 0s at the end

JavaScript: Rounding Down in .5 Cases

I am in a situation where a JavaScript function produces numbers, such as 2.5. I want to have these point five numbers rounded down to 2, rather than the result of Math.round, which will always round up in such cases (ignoring the even odd rule), producing 2. Is there any more elegant way of doing this than subtracting 0.01 from the number before rounding? Thanks.
Just negate the input and the output to Math.round:
var result = -Math.round(-num);
In more detail: JavaScript's Math.round has the unusual property that it rounds halfway cases towards positive infinity, regardless of whether they're positive or negative. So for example 2.5 will round to 3.0, but -2.5 will round to -2.0. This is an uncommon rounding mode: it's much more common to round halfway cases either away from zero (so -2.5 would round to -3.0), or to the nearest even integer.
However, it does have the nice property that it's trivial to adapt it to round halfway cases towards negative infinity instead: if that's what you want, then all you have to do is negate both the input and the output:
Example:
function RoundHalfDown(num) {
return -Math.round(-num);
}
document.write("1.5 rounds to ", RoundHalfDown(1.5), "<br>");
document.write("2.5 rounds to ", RoundHalfDown(2.5), "<br>");
document.write("2.4 rounds to ", RoundHalfDown(2.4), "<br>");
document.write("2.6 rounds to ", RoundHalfDown(2.6), "<br>");
document.write("-2.5 rounds to ", RoundHalfDown(-2.5), "<br>");
do this:
var result = (num - Math.Floor(num)) > 0.5 ? Math.Round(num):Math.Floor(num);
Another way exists that is to use real numbers (instead of 0.2 use 20, 0.02 use 2, etc.), then add floatingPoints variable that will divide the result (in your case it's 2). As a result you can operate as Number/(10^floatingPoints).
This solution is wide across Forex companies.
You can also use this function to round with no decimal part and .5 down rule (Only positive numbers):
function customRound(number) {
var decimalPart = number % 1;
if (decimalPart === 0.5)
return number - decimalPart;
else
return Math.round(number);
}
And sorry for my english.

Categories

Resources