Wednesday, August 10, 2022

[FIXED] How do I represent the return of a specific probability fraction to be shown as a float but limited to two decimal places?

Issue

So say I have something that looks like this:

def probability_color():
  if color == 'red':
    return float(3/10)

so essentially it should return .30 instead of anything longer. My specific problem includes fractions that aren't as clean as this example so I'm getting very long decimal float values in this particular scenario. Is there a simple solution that would format it rather than using something like round()?


Solution

Just use the round format in Python to help. Here is the improved code:

def probability_color():
  if color == 'red':
    # Decimal places :)
    return float('%.2f' % (1/10))


Answered By - xnarf
Answer Checked By - Pedro (PHPFixing Volunteer)

No comments:

Post a Comment

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