user1822824
user1822824

Reputation: 2488

Calculator Web App - Handling Decimals

I know JavaScript has issues with decimals because of the way computers handle them, etc. My question is how should they be handled in the context of a calculator web app?

var exampleDecimal = 1.2 + 0.64; // 1.8399999999999999 - INCORRECT

I have no idea what a user may enter, they may enter:

var exampleDecimal = (1.232 + 10.64) * 2 - 18.2 / 2.2; // 15.471272727272728 - CORRECT

I researched the topic and found that JavaScript does not have a simple solution for accurately working with decimals in the context of a basic calculator. Does jQuery? I couldn't find a solution on jQuery's reference website but I have little experience with jQuery.

Every JavaScript calculator tutorial I've found gets 1.2 + 0.64 wrong.

Upvotes: 3

Views: 177

Answers (1)

kamituel
kamituel

Reputation: 35960

jQuery won't help you there, but you can use a library for handling this. One of the popular ones is BigDecimal:

var result = new BigDecimal('1.2').add(new BigDecimal('0.64'));
exampleDecimal.toString(); // 1.84

This syntax may be a little verbose, but you can wrap it to be a little more compact:

var dec = function (spec) {
  'use strict';
  if (this === undefined) { return new BigDecimal(spec); }
  return new BigDecimal(spec);
};

And then use it as follows:

var result = dec('1.2').add(dec('0.64'));

Upvotes: 1

Related Questions