Friday, August 12, 2022

[FIXED] How to round Decimal number without using the global context?

Issue

Using python 3.6 https://docs.python.org/3.6/library/decimal.html

I can see we can specify the rounding and precision but it's only globally by setting the context.

How can I do this for a specific Decimal instance?

Something like this pseudo code:

myNumber = Decimal(1.101901)
roundedNumber = myNumber.toFixed(2, ROUND_DOWN)
# expected result ==> 1.10
roundedNumber = myNumber.toFixed(2, ROUND_UP)
# expected result ==> 1.11

So I can parse each number with the rounding and precision I want.


Solution

Use the method Decimal.quantize.

from decimal import *

myNumber = Decimal(1.101901)
roundedNumber = myNumber.quantize(Decimal('1.00'), rounding=ROUND_DOWN) # 1.10
roundedNumber = myNumber.quantize(Decimal('1.00'), rounding=ROUND_UP)   # 1.11


Answered By - Filip Bártek
Answer Checked By - David Marino (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.