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

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?

 August 10, 2022     decimal, floating-point, format, python, python-3.x     No comments   

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)
  • 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