How to detect numeric overflow/underflow in JavaScript arithmetic operations?

2024/2/27 7:13:13

I was doing a coding test today, the goal was to catch all edge cases when adding 2 integer representations of strings in JavaScript. One case I could not get was how to detect overflow/underflow for the sum stored in the IEEE 754 numeric.

Normally, in C, I'd look at the binary representation of the numeric, but in JavaScript, I can only look at 32 bits worth of the integer value.

Here's the code I had:

function string_add(a, b) {if (arguments.length !== 2)throw new Error('two arguments expected as input');// ensure we have stringsif (typeof a !== 'string' || typeof b !== 'string')throw new Error('bad parameter types');// ensure we do not have empty stringsif (a.length === 0 || b.length === 0)throw new Error('an empty string is an invalid argument');// ensure we have integer argumentsif (0 !== (+a % 1) || 0 !== (+b % 1))throw new Error('expected numeric integer strings for arguments');var sum = +a + +b;      // create numeric sum of a and b.sum+='';                // convert numeric sum to stringreturn sum;
}

Thanks in advance.

Answer

Edit: JavaScript now has a Number.MAX_SAFE_INTEGER

Actually, integers in Javascript are 53 bits of information due to the way floating point math works.

The last time I needed to do something similar I did...

var MAX_INT = Math.pow(2, 53);
var MIN_INT = -MAX_INT;var value = MAX_INT * 5;
if (value >= MAX_INT) {alert("Overflow");
}// Note. you have to use MAX_INT itself as the overflow mark because of this:
value = MAX_INT+1;
if (value > MAX_INT) {alert("Overflow test failed");
}

EDIT After thinking about it, it would be easier to say:

var MAX_INT = Math.pow(2, 53) -1;
var MIN_INT = -MAX_INT;

since that is the largest INT that you know hasn't overflowed.

http://en.ppmy.cn/q/41902.html

Related Q&A

Dynamic execution of TypeScript in the browser

I have TypeScript which asynchronously downloads another TypeScript/javascript module:(function (exports) {"use strict";var path = require(path);exports.convertData = function (data) {return …

raphael.js - converting pie graph to donut graph

Im trying to use a raphael.js example located here:http://raphaeljs.com/pie.htmlbut I want to convert the pie graph into a donut graph (have a hole in the middle of all the slices). Currently, each sli…

How to group by 15 minutes interval a json collection in Javascript

Let say we have a collection like this in Javascript:[{ date: Fri, 02 May 2014 19:05:00 GMT, value:abc },{ date: Fri, 02 May 2014 23:43:00 GMT, value:jkl },{ date: Fri, 02 May 2014 19:01:00 GMT, value:…

Clicking a button to run casperJS in PHP and echo results in same PHP page with button

I have a casperJS script which logs in multiple users with provided credentials; which returns the amount successful and failed logins as well as the usernames which succeeded and failed. I am attempti…

Checking Flash player version using Javascript [duplicate]

This question already has answers here:Cross Browser Flash Detection in Javascript(16 answers)Closed 8 years ago.Is it possible to check the version of the Flash Player installed in a browser using Jav…

Drag and drop multiple rows from one table to another table

I need to drag and drop table rows by selecting desired rows from on table to another table. First provide option to select needed rows from one table and then all the selected rows need to be drag and…

(perhaps it was deleted?) Spreadsheet Error in Google Scripts

I have a small script that grabs some data from a spreadsheet and displays it on a Google Scripts html page - for testing Im just displaying the sheet name.It works fine for me but other users get the …

Render function in reactjs

Quick question. Im learning react js. When we create a component, we provide in the render function the html template of the component to render. So far I have only seen small components with very sma…

D3.js how do I arrange nodes of a force layout to be on a circle

I have developed a force layout to represent relationships between social groups. Now I would like to get the nodes to be distributed in a circle with links joining them. What is the best way to do thi…

Daily Limit for Unauthenticated Use Exceeded Google Api Calendar

Im testing a sample code. It has always worked but suddenly i get:{"error": {"errors": [{"domain": "usageLimits","reason": "dailyLimitExceededUnre…