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.
Related
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))
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
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.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a web form and want to accept the following phone numbers in the following format:
1234567890
123-456-7890
123.456.7890
123-4567890
The first number cannot be a 0 or a 1.
How can I do this with regex/javascript? I found a few regex formulas online but none are specific to my needs
null !== thenumber.match(/^[2-9][0-9]{2}[.-]?[0-9]{3}[.-]?[0-9]{4}$/);
(Edited to give slightly better answer with boolean result)
Consider the following Regex...
[\d-[01]]\d{2}[-\.]?\d{3}[-\.]?\d{4}
Note: You examples start with a 1 which will not satisfy the above regex.
The user-provided format should be irrelevant. It makes more sense to store phone numbers as, well, numbers, i.e. digits only, and add uniform formatting when displaying them back. Otherwise you end up wit a mess in your database and you're going to have a hard time searching for numbers (if you wanted to find if given number is already in your DB then how'd you know the format it was typed in?), and you will have inconsistent formatting of numbers when displaying them.
So you'd store any of your example numbers as 1234567890, no matter what the user has typed into the form. Which means you can validate your input by stripping any non-digits, then checking the length and other conditions, like this:
function validPhone( num ){
var digits = num.replace(/\D/g,'');
// assuming 10 digits is a rule you want to enforce and the first digit shouldn't be 0 or 1
return (parseInt(digits[0],10) > 1 && digits.length == 10);
}
You could also use return parseInt(digits, 10) >= 2000000000 to validate that the number doesn't start with 0 nor 1 and has at least 10 digits.
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.