PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, August 12, 2022

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

 August 12, 2022     decimal, python, python-3.x     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

1,205,020

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © 2025 PHPFixing