A guide to confirming large numbers in JavaScript

I am currently faced with the task of filtering out numbers that are larger than 9e+65 (65 zeros). I have to create a function that takes a number as input and returns a boolean value based on whether it meets the criteria. This function should be able to handle both standard formatted numbers (42342) and scientific notation (1e5).

Here is my current approach:

const checkIfGreaterThan65Zeros = (num: number):boolean =>
  num.toString().includes("e+") ? 
    Number(value.toString().split('e+')[1]) > 65 : false

Unfortunately, this implementation has been deemed dirty by the reviewer.

Answer №1

According to MDN:

JavaScript represents numbers in a double-precision 64-bit binary format IEEE 754, with a range between ±2^−1022 and ±2^+1023 (approximately ±10^−308 to ±10^+308) and a precision of 53 bits. Integer values up to ±2^53 − 1 can be accurately represented.

You don't need to worry about dealing with extremely large numbers. The link to the full MDN quote is provided at the end of this excerpt for detailed information on 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 reading, here is the source link.

Answer №2

Your method appears to be logically sound, however, in order to streamline the approach and make it more organized, I suggest a cleaner alternative.

While achieving the same outcome, this revised version enhances readability and allows for easier future modifications. By breaking down the logic and results into descriptive variables, potential errors or oversights can be easily identified.

In addition, you can simplify the process by directly obtaining the index without splitting the data, thus avoiding confusion caused by dealing with multiple types (array, string, number). This modified strategy maintains consistency 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))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Utilizing Javascript filtering to narrow down results based on date ranges within a Vue

I'm currently using Vue within a Laravel application. Most of the functionality is working as expected, except for the last part. I've been struggling to come up with the right search terms for this scenario. Apologies if this question has alread ...

Using AngularJS to display a targeted row in a table

I am currently working with a basic table and using ng-repeat to display rows in the table. I have a specific requirement where I want to show an additional row when a regular row is clicked. This additional row should contain custom markup in just one co ...

Struggling to access the height attribute from a CSS file

Hey there. I'm pretty confident that the solution to my query is quite simple. So, I have a .css file with this particular code snippet: div.site { text-align:center; border:2px solid #4b6c9e; padding:1px; margin-top:10px; font-size:medi ...

To prevent flickering when using child flex elements, it's best to use position fixed along with a dynamically updated scrollbar position using Javascript

My navigation component includes a slim banner that should hide upon scroll and a main-nav bar that should stick to the top of the screen and shrink when it does so. I initially looked into using Intersection Observer based on a popular answer found here: ...

Steps for setting up i18nextStart by including the i

I am working on developing a multilingual app using the i18next package. Unfortunately, I am experiencing issues with the functionality of the package. Below is an example of the i18next file I have been using: import i18n from "i18next"; impor ...

Can you explain the purpose of the statement `var MyConstructor = function MyConstructor()`?

Can you explain the distinction between these two code snippets: var NodestrapGenerator = module.exports = function NodestrapGenerator() { yeoman.generators.Base.apply(this, arguments); // more code here }; and: var NodestrapGenerator = module.expor ...

Tips for merging Next.js configuration settings

My current configuration settings are as follows: module.exports = { images: { domains: [ "ticket-t01.s3.eu-central-1.amazonaws.com", "media.istockphoto.com", ], deviceSizes: [320, 375, 450, 540, 640, 750, 828, ...

Preventing a draggable item from being dropped into a sortable container when the maximum count has been reached

Check out the following code snippet: <link rel="stylesheet" href="//code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.10.2.js"></script> <script src="//code.jquery.com/ui/1.11.0/jquer ...

"Although there are no errors, the ng-switch directive within the ng-repeat is not functioning as

I'm working on setting up a simple image gallery where I can dynamically change the displayed image by setting a specific number for currentImage. Check out my HTML code: <div class="main_image" ng-switch on="current_image"> <img ng-rep ...

Scrolling to the bottom of the page triggers jQuery to load additional content

Is your jQuery script not working properly when attempting to load more content upon reaching the bottom of the page? It seems to be functional on Safari/iPad and Android Mozilla browsers, but encountering issues on default Android and Chrome browsers. ...

Unable to assign a class to the menu option

I'm encountering an issue with the following code: JavaScript $(document).ready(function() { var url = window.location; var element = $('#nav1 li a').filter(function() { return this.href == url || url.href.indexOf(this.href) == 0; ...

How can I update a dropdown menu depending on the selection made in another dropdown using Angular

I am trying to dynamically change the options in one dropdown based on the selection made in another dropdown. ts.file Countries: Array<any> = [ { name: '1st of the month', states: [ {name: '16th of the month&apos ...

Eslint is signaling an error when the keyword "async" is used in the most recent version of Node for Firebase Functions

I'm venturing into using Firebase Functions for my project, but as a newcomer to Javascript, I've been struggling for a week now and hit a roadblock with the following issue. Below is the snippet of my code: exports.postcleanup = onSchedule("eve ...

Rearranging a JSON Object post editing

Currently, I am working on a project where I need to display and sort a list of items based on a JSON object. This includes sorting by both string values and integers within the object. So far, I have been successful in listing and sorting the items by st ...

Stop :hovering on the link for iPad

My webpage contains sublinks with CSS properties as follows: #leftNav .searchBySub {...} #leftNav a.searchBySub:hover {...} #leftNav .searchBySubClicked {...} However, I have observed that on the iPad, the :hover styles are being applied. Is there a wa ...

Instructions on creating a Superfish menu with a vertical layout in the first level and a horizontal layout in the second level

Currently, I am using the Superfish menu in Drupal7 and have designed my first item level to be vertical. However, I now want to style my second item level horizontally. I have tried various CSS approaches and added some class names via jQuery like $(&apo ...

Eliminate the hovering effect from images that are hyperlinked

I am feeling incredibly desperate as I have spent hours searching the internet for a solution with no success. When it comes to text links, I have included the following CSS code: a:hover img { border-bottom: none !important; } However, this code is als ...

Getting the value of a lookup in an alert or console within a Material table in React

I am currently integrating a material table into my project and I have encountered an issue. Instead of getting the name of a city, I am receiving numbers like 63 or 32 in alerts or console logs. For reference, here is the link to the CodeSandbox: https:/ ...

Ways to organize backbone models, views, and collections using vim?

I am a fan of vim's folding feature, but I have encountered some challenges when trying to fold backbone models, views, and collections. This is because backbone does not follow the traditional prototype syntax, but instead uses a .extend() based synt ...

What is the best way to adjust menu alignment for big screens?

Is there a way to set the alignment of a dropdown menu to the right specifically for large screens? <div class="btn-group"> <button type="button" class="btn btn-secondary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expande ...