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

Sunday, August 7, 2022

[FIXED] How do I force a python Decimal to have atleast two decimals?

 August 07, 2022     decimal, python     No comments   

Issue

I would need to format a python Decimal object to have atleast two decimals, but no more than 5. Is there a reliable way to do this? Examples:

1.6 --> 1.60
1.678 --> 1.678
1.98765 --> 1.98765

If there are more than two decimals, it is vital that it does not get truncated to only two decimals.


Solution

It looks to me like there are two parts to this question - one, determining the correct number of digits and two, quantizing the values to that number of digits.

To do the first, I would get the current exponent using the as_tuple() method. Unless I'm overlooking something simpler.

>>> import decimal
>>> d = decimal.Decimal("1.678")
>>> d.as_tuple().exponent
-3

>>> d2 = decimal.Decimal("1.6")
>>> d2.as_tuple().exponent
-1

So from that you can compute the desired exponent:

MAX_EXPONENT = -2
MIN_EXPONENT = -5
def desired_exponent(d):
    current_exponent = d.as_tuple().exponent
    return min(MAX_EXPONENT, max(MIN_EXPONENT, current_exponent))

The second is answered by the accepted answer on the marked duplicate - use the quantize() method. You'll need to construct a Decimal value with the desired exponent you can provide as the argument to quantize(). There are multiple ways to do that, but two simple ones are exponentiating decimal.Decimal("10") or using the tuple constructor for decimal.Decimal().

>>> quant_arg = decimal.Decimal("10") ** -2
>>> decimal.Decimal("1.6").quantize(quant_arg)
Decimal('1.60')

Or:

>>> quant_arg = decimal.Decimal((0, (), -2))
>>> decimal.Decimal("1.6").quantize(quant_arg)
Decimal('1.60')

I used -2 as a literal there, you'd want to use the calculated value of desired_exponent.

There are multiple ways to organize this code, I think the parts that are not obvious are a) accessing the current exponent of a decimal value and b) some of the ways of constructing an arg for quantize(). And this is all assuming you need the actual decimal objects, and aren't just outputting them - if this is a question just about output formatting re-quantizing is probably overkill.



Answered By - Peter DeGlopper
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

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 © PHPFixing