Need help on newbie coding (python) [duplicate] - python

This question already has answers here:
How to print float to n decimal places including trailing 0s?
(5 answers)
Closed 2 years ago.
It's my first week trying to learn how to code.
Rods is input from user so it can be whatever
miles = round(Rods * 0.003125, 20)
print("Distance in Miles = ", miles)
I need this line of code to print 20 decimals. I thought by adding comma 20 it would do so. I then tried looking re-writing it to format{miles: "20.f"}. (Don't remember exactly how the code went)
Any guidance would be appreciated.

Try this snippet:
miles = Rods * 0.003125
print("Distance in Miles = {:.20f}".format(miles))
This code does the calculation first and formats the answer such that it is displayed in 20 decimal places. For displaying only 10 decimal places change to .10f, for 2 decimal places change to .2f and so on.

When calling round() method on floats, the unnecessary leading decimal zeros are not counted, since the number is the same.
You can convert the number to string, use .split(".") on it to separate the decimal and whole number
example: "3.85".split(".") will return a list whose elements are ["3", "85"] digits = str(num).split(".")
Lets take the second element, decimals decimals = digits[1]
Then you take the length of second element that is decimals and subtract it from 20. This will be the amount of zeros to add. newDecimals = decimals + (20 - len(decimals)) * "0"
Now, use the list from before to form a new number
final = digits[0] + "." + newDecimals
Keep in mind that converting it back to a float will remove those zeros.

Try following source code :
miles = Rods * 0.003125
miles_formatted_float = "{:.20f}".format(miles)
print("Distance in Miles = "+miles_formatted_float)

Related

getting wrong number when too many decimals [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 10 months ago.
In this program, I am asking the user to input two datetime, and I convert the differences between the two date times into several floats. difference_days is one of the float of total difference in days.
so basically, I am writing this in for loop
part of my code is below:
if difference_days.is_integer():
print(f'The difference is {int(difference_days)} days.')
else:
hours = (difference_days - int(difference_days))*24.0
print(int(difference_days))
print(difference_days)
print(difference_days - int(difference_days))
print(hours)
if difference_hours.is_integer():
print(f'The difference is {int(difference_days)} days and {int(hours)} hours.')
else:
... # other codes that handle minutes, seconds, microseconds
I did not post all the codes, because I think there's something wrong with the calculation in python.
so those print statements between hours and the second if statement is just for test, and below is the output:
91
91.95833333333333
0.9583333333333286
22.999999999999886
I was confused why the third one starts to have more decimal places in the end while the second doesn't. How should I fix that? I would like it to only display the 12 decimals.
You can just use the format() function, and convert it to a floating point, like this:
float(format(difference_days,".12f"))
This will return difference_days as a floating point with 12 decimals
Well I guess I just found the solution, so I did the following, but any better ideas?
from decimal import *
getcontext().prec = 12
hours = (Decimal(difference_days) - int(difference_days))*24
Floating points can't be perfectly represented in binary, so you will always have the weird error at the end.
Why are floating point numbers inaccurate?
But you can print the 12 digits of the decimal with:
>>> x = 0.9583333333333286
>>> f'{x:.12f}'
'0.958333333333'
>>> float(f'{x:.12f}')
0.958333333333

Python round - Two deciding decimals [duplicate]

This question already has answers here:
How to round a number to significant figures in Python
(26 answers)
Closed 1 year ago.
I want to round numbers so that two numbers are used after the last zero, or decimal if the number is greater than 1. I've looked up the documentation for round, but can't seem to find this feature.
If I use round, it always round to n decimals places regardless.
This is the output I'm looking for:
42.0068 --> 42.01
0.00251 --> 0.0025
420.246 --> 420.25
0.192 -> 0.19
0.00000000128 --> 0.0000000013
The kind of rounding you're asking for isn't a common operation.
In terms of common operations you have two cases (ignoring sign since all your examples are positive):
If the value is less than 1, round to significant figures (eg per the link in #quamrana's comment on the question).
Else (ie the value is at least 1), round to decimal places in the usual way.
Your final code would reasonably be a function with a simple if-else:
def round_special(value):
if value < 1:
return round_to_sf(value, 2)
else:
return round_to_dp(value, 2)
You could try with string manipulation. It's not that elegant, but seems to work. It's up to you to complete this code to handle exceptions..
if number>1:
result = round(number,2)
else:
str_number = str(number)
i = str_number.rfind('0')
result = float(str_number[:i+3])

Can't add commas and also remove hanging zeros of big numbers in Python

I'm making a simple program where it calculates your average salary per year by just asking a couple questions. So when it calculates it I want it so it has commas and gets rid of hanging zeros.
calculation = (hourly_rate * hours) * 52
format = "{:,}".format(calculation)
format_2 = "{:2f}".format(float(calculation))
#Formatting big numbers to include commas
print("{0}, your average salary for the {1} job, is ${2} per year."
.format(name, occupation, format_2))
The math is 13.65 * 32 * 52 = 22,713.6
But my output is: $22713.600000
What I want: $22,713.06
I believe you're missing a period. I've also simplified things a little:
calculation = (float(input(f"How many hours do you work in a typical week? ")) * float(input(f"Your hourly rate is: "))) * 52
print("Your average salary is ${:,.2f}".format(calculation))
Your second variable format is a python special word, try to call it format_1, and this
should help you
You can use round function to remove zeros
round(decimal,1) # 1 is number of digits you want to round off
And check this link for the commas - Commas

Python: Setting up a binary-number string converter, then indexing the result

I have a bit of an challenge before me.
Currently I'm trying to accomplish this process:
Feed a decimal, or any number really, into a binary converter
Now that we possess a binary string, we must measure the length of the string. (as in, numstr="10001010" - I want the return to count the characters and return "8")
Finally, I need to extract a section of said string, if I want to cut out the first half of the string "10001010" and save both halves, I want the return to read "1000" and "1010"
Current Progess:
newint=input("Enter a number:")
newint2= int(newint)
binStr=""
while newint2>0:
binStr= str(newint2%2) + binStr
newint2= newint2//2
print (binStr)
newint = input("Enter a binary number:")
temp=newint
power = 0
number = 0
while len(temp) > 0:
bit=int(temp[-1])
number = number + bit * 2 ** power
power+=1
temp = temp[:-1]
print(number)
//This works for integer values, how do I get it to also work for decimal values, where the integer is either there or 0 (35.45 or 0.4595)?
This is where I'm lost, I'm not sure what the best way to attempt this next step would be.
Once I convert my decimal or integer into binary representation, how can I cut my string by varying lengths? Let's say my binary representation is 100 characters, and I want to cut out lengths that are 10% the total length, so I get 10 blocks of 10 characters, or blocks that are 20% total length so I have 5 blocks of 20 characters.
Any advice is appreciated, I'm a super novice and this has been a steep challenge for me.
Strings can be divided up through slice notation.
a='101010101010'
>>>a[0]
'1'
>>>a[0:5]
'10101'
>>>a[0:int(len(a)/2)]
'101010'
That's something you should read up on, if you're getting into Python.
Here is my suggestion, based on answer from What's the best way to split a string into fixed length chunks and work with them in Python? :
def chunkstring(string, percent):
length = int(len(string) * percent / 100)
return ([string[0+i:length+i] for i in range(0, len(string), length)])
# Define a string with 100 characters
a = '0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789'
# Split this string by percentage of total length
print(chunkstring(a, 10)) # 10 %
print(chunkstring(a, 20)) # 20 %

Adding a round down feature on a program

My program is meant to allow the user to create a character that has two attributes with values. The attributes are called strength and skill. The attribute values are created by a random number between 1 and 12 being divided by a number between 1 and 4. The outcome is added to 10. The thing is decimals can occur, so i want my program to round down decimals. I want it to round down even if the number is for example 5.6. Then is would become 5. I have not a clue how to implement this to my current code. I would also like the information to be saved to a text file but this is less important. I'm a noob at python and i would appreciate the help, thanks.
My current code
from random import randint
Strenght = 10
Skill = 10
while True:
character = str(input("Enter name of your character\n"))
if character:
print("Your characters name is",character)
print("They have",Strenght + randint(1,12)/randint(1,4),"Strenght")
print("And",Skill + randint(1,12)/randint(1,4),"Skill")
if input("Would you like to make another character? \n").lower() not in ("yes","y"):
break
You want to use the math.floor() command. It always rounds down.
>>> import math
>>> print (math.floor(5.6))
5.0
You can also round up with math.ceil() or round to the nearest integer with round().
Since both of the numbers you're dividing are integers, you can use the integer divide // to produce an integer output with the remainder dropped.
>>> print 17 // 3
5
>>> from __future__ import division
>>> print 17 / 3
5.66666666667

Categories