MikeMcl / decimal.js

An arbitrary-precision Decimal type for JavaScript
http://mikemcl.github.io/decimal.js
MIT License
6.35k stars 480 forks source link

Looping new Decimal("0.02").plus(new Decimal("0.01")) #184

Closed marcius-tan closed 2 years ago

marcius-tan commented 2 years ago

So i want to loop new Decimal("1.12098") object in which for every run it adds new Decimal("0.00001")

import Decimal from "decimal.js-light";

let obj = new Decimal("1.12098");
const step = new Decimal("0.00001");

for(let ii = 0; ii<=10; ii++) {
  console.log(obj.plus(step));
}

result i get is all 1.12099 for 11 times: 1.12099 1.12099 ... 1.12099

Can anyone show how to do it? Thx again.

marcius-tan commented 2 years ago

I found it i do it this way :

import Decimal from "decimal.js-light";

let obj = new Decimal("1.12098");
let newObj;
const step = new Decimal("0.00001");

for(let ii = 0; ii < 10; ii++) {
   newObj= obj.plus(step).toString();
   console.log(newObj);
   obj = new Decimal(newObj);
}

I hope it is a correct way of doing it. 👍

MikeMcl commented 2 years ago

The correct way is:

obj = obj.plus(step);