What specific characteristic of TypeScript's number data type or the Math.ceil() function is responsible for this calculation mistake?

Currently, I am working on a function in Typescript that is supposed to generate a unique number each time it runs. However, there seems to be a problem with the arithmetic as the results are not always correct. Upon further examination of the code below, I suspect that the issue might be related to the behavior of Typescript/Javascript's number type or Math.ceil() function. I would greatly appreciate any insight or advice on how to resolve this.

function createUniqueNumber(){
    const millidate = (new Date()).getTime();
    const factor:number = 10000;
    const codeTime:number = +millidate*factor;
    const randomEnd:number = Math.ceil(Math.random()*factor);
    const randomMult:number = Math.ceil(Math.random()*10);
    const codeBody:number = codeTime+randomEnd;
    const uniqueCode:number =  codeBody*randomMult;
    console.log("Breakdown of " + uniqueCode + ": ", codeTime, randomEnd, codeBody, randomMult);
    return uniqueCode;
};


createUniqueNumber();

Here is an image showcasing some tests conducted in Playground:

https://i.sstatic.net/bcdsh.png

I have been using Typescript's Playground for testing purposes, but the performance does not seem to vary significantly across different environments.

Answer №1

It has been highlighted in the feedback that your numerical values exceed the system threshold. On my 64-bit platform, Number.MAX_SAFE_INTEGER is:

9007199254740991 <- System limit
163469121917820770 <- Your current value

You should consider reducing the values or converting them into strings.

Answer №2

If you want to work with extremely large numbers (beyond the limit of Number.MAX_SAFE_INTEGER), it is recommended to utilize the BigInt() feature.

Comparison without using BigInt:

9007199254740991 + 1 = 9007199254740992 // Correct
9007199254740991 + 2 = 9007199254740992 // Incorrect
9007199254740991 + 3 = 9007199254740994 // Correct

Utilizing BigInt for accurate calculation results:

9007199254740991n + 1n = 9007199254740992n // Correct
9007199254740991n + 2n = 9007199254740993n // Correct
9007199254740991n + 3n = 9007199254740994n // Correct

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

Searching for documents in MongoDB using minimum as a condition in the query

My user base is expansive, each facing a unique set of problems at different times. I am currently searching for users or documents that share a specific problem type (referred to as "top":1) but only among those, I am interested in isolating the entry wit ...

Utilize only certain JSON properties within JavaScript

I have access to an array of JSON objects. [ { Id: "1", StartNo: "1", ChipNo: "0", CategoryId: "0", Wave: "0", Club: "", FirstName: "Lotta", LastName: "Svenström", FullName: "Lotta Svenström", ZipCode: "24231" }, {...} ] My goal is to create a new data ...

Is there a way to utilize req.query, req.params, or req.* beyond its original scope without the need to store it in a database?

Looking to streamline my code and apply the DRY pattern, I've been working on creating a helper function for my express http methods. The structure of each method is similar, but the req.params format varies between them. Here's how I attempted t ...

An arrow function fails to activate

Here is the code snippet that I am dealing with: class App extends React.Component { loginComponent = <button onClick={this.signUp}>Sign Up</button>; signUp = () => { alert("test"); } rende ...

Formik QR code reader button that triggers its own submission

I recently developed a custom QR code reader feature as a button within the Formik component customTextInput.tsx, but I encountered an issue where clicking on the button would trigger a submission without any value present. The following code snippet show ...

Tips on using constructor functions and the new keyword in Typescript

This is a demonstration taken from the MDN documentation showcasing the usage of the new keyword function Car(make, model, year) { this.make = make; this.model = model; this.year = year; } const car1 = new Car('Eagle', 'Talon TSi&apos ...

Getting around CloudFlare's 100-second time-out restriction

Seeking a solution to AJAX-enable my reports and circumvent the 100-second time-out constraint enforced by CloudFlare for requests passing through its platform. For more information, visit Is it possible to increase CloudFlare time-out? The implementatio ...

invisible recaptcha with synchronous ajax

Hey, I'm trying to figure out a solution on how to obtain the token or a valid response from Recaptcha and then proceed with running the ajax call. Does anyone have any suggestions on how to achieve this in a synchronous manner? Here's the proce ...

The property 'caseSensitive' is undefined and cannot be read

After creating a simple code, I am puzzled by an error message that seems to be case sensitive. However, the code appears correct based on my understanding. Here is the code snippet: App.js const express = require('express'); const path = requir ...

Identify support for the :first-child pseudo-class

Is there a way to determine with JavaScript whether the browser is compatible with the CSS :first-child selector? ...

Is there a way to automatically incorporate a component into every view within a Next.js application?

Is there a more efficient and less cumbersome way to import components for every view in a Next.js app? I am interested in incorporating the "arwes" framework into my project and utilizing components from . One of the examples of a component I will be usin ...

Elements powered by jQuery failing to load upon dynamic webpage(s) loading via ajax

Dynamic loading of jQuery elements, such as Ibuttons, seems to be causing issues when implemented with an ajax dynamic content loader. The entirety of my website is rendered through Ajax just like this: <html> <header> {jQuery} </header> ...

Tips for personalizing the css styles of an alert box?

I am in need of customizing the alert box using CSS attributes. Currently, I am able to achieve a similar effect with the code below: JQUERY: $('<div class="alertMessage">Error first</div>') .insertAfter($('#componentName' ...

REGEX: All characters that appear between two specified words

Is it possible to use Regex to select all characters within the designated words "Word1 :" and "Word2 :"? I am looking to extract any character located between these two specific phrases. Word1 : Lorem ipsum dolor sit amet consectetur adipiscing elit ...

Issue with FileStreamResult not triggering download prompt after AJAX call in MVC

I am encountering an issue with my code that is triggered by the "export" li tag. It converts a FusionChart to an SVG string and then sends it to my controller via an ajax call. The problem I'm facing is that even though the controller receives the r ...

dynamically import a variety of components in vue.js and nuxt depending on certain conditions

Is there a way to implement dynamic imports for all 3 components in this scenario? Each component has different props, so using the switch option in the computed method is not feasible. I have come across solutions for using a single component dynamically ...

Guide on restricting object keys to a specific set of strings in typescript

I am dealing with an API that has the ability to return one of these options: { fill: 'string'} or {stroke: 'string'} or {effect: 'string'} The key type I have established is as follows: type StyleKeyType = | 'fill&a ...

Ways to display tinyMCE content in a unique manner

I've been diving into node.js/express/mongoDB and decided to create a blog. I encountered an issue with rendering the content inputted through tinyMCE as HTML - instead, it's displaying the tags around my content. How can I properly display it as ...

Tips for running two elixir tasks consecutively?

Check out this piece of code: var gulp = require('gulp'), fs = require('fs'); gulp.task('taskOne', function() { return gulp.src('folder1/file1.js') .pipe(gulp.dest('folder2')); }); gulp.t ...

What is the ideal destination for my Ajax request to be sent?

When utilizing jQuery, in the event of sending an Ajax request you must provide the URL to direct towards. For instance: $.get("someurl", function(data) { console.log(data); }); The query at hand is: should the URL indicate a page on the server, trea ...