MikeMcl / decimal.js

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

Question to precision #142

Closed elementalTIMING closed 4 years ago

elementalTIMING commented 4 years ago

Hi,

after having a lot of trouble with floating point calculations in JS I found your library and it really looks great. But there is a points I don't understand and hope that you can give some support:

Do I have the possibility not to round but to truncate a calculation? What I need is e.g. 123.6787564 shall be truncated after 3 digits so that the result becomes: 123.678 (no rounding in any case). Is this possible too? I couldn't find anything like that in your documentation...

Thx for your help, Lars

MikeMcl commented 4 years ago

To truncate use rounding mode Decimal.ROUND_DOWN, i.e. round towards zero.

For example:

let x = new Decimal(123.6787564);
x = x.toDecimalPlaces(3, Decimal.ROUND_DOWN);
x.toString();    // "123.678"

Or you could just use toFixed, for example:

x.toFixed(3, Decimal.ROUND_DOWN);    // "123.678"

or if you want all operations to round down use

Decimal.set({ rounding: Decimal.ROUND_DOWN });

x.toFixed(3);                        // "123.678"
x.toDecimalPlaces(3).toString();    // "123.678"
elementalTIMING commented 4 years ago

Thank you for your respond. That with Decimal.ROUND_DOWN I understood. But it is a rounding... My point is, that it is not allowed to round (not UP and not DOWN). I need a real "cut" after x-digits. Is this possible too?

MikeMcl commented 4 years ago

Using ROUND_DOWN is exactly the same as a real cut after x digits. Truncation is still a form of rounding.

Open a browser console here and experiment with it.

elementalTIMING commented 4 years ago

Using ROUND_DOWN is exactly the same as a real cut after x digits. Truncation is still a form of rounding.

Open a browser console here and experiment with it.

Thank you very very much!