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

Thursday, August 11, 2022

[FIXED] How to generate a random number to 2dp

 August 11, 2022     decimal, python, rounding     No comments   

Issue

I am trying to work on a random number generator which produces a random number which is to 2dp regardless of whether it needs to be. eg. 2.10 is 2.10 not 2.1, 3 = 3.00

import random

temp_var_4_int = random.randint(2,5) + round(random.random(),2)

print (temp_var_4_int)

It should randomize a number between 2 and 5 and then add a decimal to it which is rounded to 2 decimal places but I keep getting answers such as:

1.2700000000000002 instead of 1.27

I'm not sure why it's throwing this anomaly at me.


Solution

assuming you want your numbers in [0, 10] you could just do this:

from random import uniform

r = round(uniform(0, 10), 2)
print(f"{r:3.2f}")

if r = 2.1 the format string will represent it as "2.10"; but for all mathematical purposes the trailing zero has no effect.



Answered By - hiro protagonist
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