Why javascript don't have a random function to generate integers? [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I'm using this function to generate random int values :
var r = function(min, max){
return Math.floor(Math.random() * (max - min + 1)) + min;
};
It works perfectly but makes me wonder ... why there is no randomInt and randomFloat in javascript?

JavaScript has a Number type which is a 64-bit float; there is no Integer type per se. Math.random by itself gives you a random Number, which is already a 64-bit float. I don't see why there couldn't be a Math.randomInt (internally it could either truncate, floor, or ceil the value). There is no good answer as to why the language doesn't have it; you would have to ask Brendan Eich. However, you can emulate what you want using Math.ceil or Math.floor. This will give you back a whole number, which isn't really an Integer typewise, but is still a Number type.

Because Javascript doesn't have those types. Pure javascript only has a generic number type.
More info on Javascript types may be found here and here.
You may also want to look into this question: Integers in JavaScript
The marked answer says, and I quote:
There are really only a few data types in Javascript: Objects, numbers, and strings. As you read, JS numbers are all 64-bit floats. There are no ints.

Related

How to verify huge number in JS [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 10 months ago.
Improve this question
I have a task to filter out a number which is bigger than 9e+65 (65 zeros).
As input I have a number and as output I need to return a boolean value. The function can accept regular formatted numbers (42342) and any scientific notation (1e5).
My approach is:
const 65zerosCheck = (num: number):boolean =>
num.toString().includes("e+")
: Number(value.toString().split('e+')[1]) > 65
: false
It looks dirty and the reviewer didn't accept it.
To quote MDN:
In JavaScript, numbers are implemented in double-precision 64-bit binary format IEEE 754 (i.e., a number between ±2^−1022 and ±2^+1023, or about ±10^−308 to ±10^+308, with a numeric precision of 53 bits). Integer values up to ±2^53 − 1 can be represented exactly.
You do not have to worry about such huge numbers. I have added a link to MDN quote above at the end of this snippet where it is discussed in details about how Javascript handles Numbers.
const HUGE_NUMBER_THRESHOLD = 9e+65;
const checkHugeNumbers = (num) => num > HUGE_NUMBER_THRESHOLD;
let myTestNum = 9000000000000000000000000000000000000000000000000000000000000000000;
console.log(checkHugeNumbers(myTestNum));
// OUTPUT:
// true
For further study, here is the reference link.
There doesn't seem to be anything logically wrong with your approach, but if your reviewer is asking for a cleaner approach, this is my suggestion.
It does the same thing, but is more readable and its easy to add on to, in the future. Splitting up the logic and results into descriptive variables makes it easier to read, and catch any errors or oversights that may be encountered.
Also you can save a step by directly getting the index, without using split and creating three types (array, string, and number), that can make it confusing to follow. This approach keeps everything between strings and numbers
const checkOver65Zeros = (num: number) =>{
const numString = num.toString()
const idxOfZeros = numString.indexOf("e+")
if(idxOfZeros!== -1)
return Number(numString.substring(idxOfZeros + 2)) > 65
return false
}
console.log(checkOver65Zeros(900000000000000000000000000000000000000))

Convert 17digit number string to a integer [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I want to convert a 17digit number string into a number
this is the number "76561197962169398".I tried using parseInt()
The result of using parseInt is :-
76561197962169390
I am loosing the last digit.I also tried BigInt() 'n' is getting appended to the number.
I m thinking of using replace() with a regex for only digits.
Is there any other way I can achieve this without loosing precision.
Please any help regarding this is really appriciated.THANK YOU
in chrome 83 devtools:
x=76561197962169398n
76561197962169398n
++x
76561197962169399n
typeof x
"bigint"
y=BigInt("76561197962169398")
76561197962169398n
++y
76561197962169399n
x+y
153122395924338798n
x + 1
VM342:1 Uncaught TypeError: Cannot mix BigInt and other types, use explicit conversions
at <anonymous>:1:2
(anonymous) # VM342:1
x + 1n
76561197962169400n
[5n, 3n, 9n, 7n].sort()
[3n, 5n, 7n, 9n]
The n suffix is for display - and in code it's needed to say a literal value needs to be treated as bigint instead of number - think of it like quotes for strings - without quotes a sequence of characters is not a string - similarly a number without n suffix is not a bigint - it's a number that has limited precision and simply cannot be used for large values

convert any string like "10", "-0.129894", "12.02102" to number without adding or loosing anything [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
As you can see from the title I have various cases for strings that can contain numbers in them. I found out that using parseInt() and parseFloat() didn't work for me as parseInt will convert number like 10.28 to just 10, but parseFloat will make number like 10 into 10.0, I want to somehow convert string into number so it stays exactly like it was in the string without anything removed or added.
Per MDN Number ( MSDN page also, but not so much info ).
At the top of the page:
The primary uses for the Number object are:
If the argument cannot be converted into a number, it returns NaN.
In a non-constructor context (i.e., without the new operator), Number can be used to perform a type conversion.
At the bottom of the page, there are some examples:
Convert numeric strings to numbers
Number("123") // 123
Number("") // 0
Number("0x11") // 17
Number("0b11") // 3
Number("0o11") // 9
Number("foo") // NaN
Number("100a") // NaN
Demo https://jsfiddle.net/hxkfafdw/
More on the topic - Number("foo") is NaN Number("f00") - same. Number("0xf000") - this is a hex number.

JavaScript math issue [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I see this in JavaScript
2-(1/3 * 1) // => Returns 1.66666666667
but,
4-(1/3 * 7) // => Returns 1.6666666667
This is one less 6 than the previous result. This is awkard, because both expressions are suposed equal to 5/3
I tried to do the same thing using Python, and both expressions returned the same result.
This is because the intermediates are an order of magnitude different:
0.3333333333333333 * 1
#>>> 0.3333333333333333
0.3333333333333333 * 7
#>>> 2.333333333333333
This means that the first will be rounded to an 8x greater granularity than the second. Because of Python's repr being pretty and rounding to the nearest decimal that evaluates exactly to the floating point, this shows up as a 10x difference in granularity.
To compare visually:
0.3333333333333333
2.333333333333333
See how they have the same number of significant figures but a different number of decimal places.
When you do number - multiplication, you end up "unshifting" this value, so its ends up with more error than before in relative terms, although the exact (absolute) error is the same.

How do I result in a Float number with 2 integers? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
var ratings = 3193;
var reviews = 9;
var average = parseFloat(ratings) / reviews; //I want a floating point number at the end.
Is this the right way to do it?
All numbers in JavaScript are double-precision 64-bit binary format IEEE 754. There is no need to typecast "integers" into "floats" as you would expect it from C/C++ and other languages. You need parse* only if you handle strings.
See also:
Number value
primitive value corresponding to a double-precision 64-bit binary format IEEE 754 value
parseInt, parseFloat (both take a string as parameter)
The conversion isn't necessary. JavaScript automatically converts between types. And numbers are not actually represented as integers internally. They're all floating point anyway.
So, the simplest solution should have the desired effect:
var ratings = 3193;
var reviews = 9;
var average = ratings/reviews;
What you have in your example causes the engine to convert ratings to a String and parse that string as a double (theoretically resulting in the value it had to begin with) before treating it as the numerator in your calculation.

Categories