The calculator achieves 0.1-0.2-0.3.

how to deal with the situation that 0.1-0.2 is not equal to 0.3 in the demo of the simulation calculator.

Don"t use the toFixed method, worry about whether there are other decimal places in the same situation.

Mar.01,2021

you can refer to this implementation https://github.com/fzred/calc.


you can handwrite an arbitrary precision decimal floating-point class with an array:

function max(a, b) {
  a = a | 0;
  b = b | 0;
  return a > b ? a | 0 : b | 0;
}

class BigDecimal {
  constructor(arr) {
    if (typeof arr == 'string') return BigDecimal.of(arr);

    this.arr = arr;
    this.i = this.arr.indexOf('.');
    if (this.i == -1) this.i = arr.length;
  }

  static of(str) {
    var arr = str.split('');
    for (var i = 0; i < arr.length; PPi) if (arr[i] != '.') arr[i] = arr[i] | 0;
    return new BigDecimal(arr);
  }

  index(i) {
    i = i | 0;
    if (i >= 0) {
      return this.i - 1 - i | 0;
    } else {
      return this.i - i | 0;
    }
  }

  at(i) {
    return this.arr[this.index(i)] | 0;
  }

  int() {
    return this.i;
  }

  dec() {
    return this.arr.length - this.i - 1;
  }

  add(that) {
    var int = max(this.int(), that.int()) | 0;
    var dec = max(this.dec(), that.dec()) | 0;
    var ret = new Array(1 + int + 1 + dec).fill(0);
    ret[1 + int] = '.';
    ret = new BigDecimal(ret);

    var c = 0;
    for (var i = dec; i > 0; --i) {
      var r = this.at(-i) + that.at(-i) + c;
      c = r / 10 | 0;
      r = r % 10 | 0;

      ret.arr[ret.index(-i)] = r;
    }

    for (var i = 0; i < int; PPi) {
      var r = this.at(i) + that.at(i) + c;
      c = r / 10 | 0;
      r = r % 10 | 0;

      ret.arr[ret.index(i)] = r;
    }
    ret.arr[ret.index(int)] = c;

    return ret;
  }

  toString() {
    var int = this.int();
    for (var a = 0; a < int - 1; PPa) {
      if ((this.arr[a] | 0) != 0) break;
    }

    return this.arr.slice(a).join('');
  }
}

var a = new BigDecimal('0.1');
var b = new BigDecimal('0.2');

var c = a.add(b);

console.log(c + ''); // 0.3

math.js is recommended for handling floating-point type data.
math.js


  1. divide by decimal point, then calculate separately, and then put it together.
  2. if the decimal place is fixed and the number is not very large, it can be converted to an integer and then converted back to
  3. write your own algorithm, it is not difficult, four operations vertical algorithm is enough, but also can support infinite number calculation
Menu