limited float decimal point without rounding the number [duplicate] - python

This question already has answers here:
How to truncate float values?
(31 answers)
Closed 4 years ago.
I want convert a number to a float number with 3 decimal point but I want it without rounding.
For example:
a = 12.341661
print("%.3f" % a)
This code return this number:
12.342
but I need to original number,I need this:
12.341
I write a code that receive a number form user and convert it to a float number.
I have no idea that what is the number entered with user.

My first thought was to change print("%.3f" % a) to print("%.3f" % (a-0.0005)) but it does not quite work: while it outputs what you want for a=12.341661, if a=12.341 it outputs 12.340, which is obviously not right.
Instead, I suggest doing the flooring explicitly using int():
a = 12.341661
b = int(a*1000)/1000.
print(b)
This outputs what you want:
12.341
To get 3 decimals out even if the input has fewer, you can format the output:
a = 3.1
b = int(a*1000)/1000.
print("%.3f" % b)
Outputs:
3.100

try str and slicing
a = 12.341661
b = str(int(a))
c = str(a - int(a))[1:5]
d = b + c
print(d)

Related

is there a function in python to round off three digits after decimal but show all three digits even if zero [duplicate]

This question already has answers here:
Rounding a number in Python but keeping ending zeros
(6 answers)
Closed 3 months ago.
i want to round off number 7.00087 and output should be 7.000
I tried round() function but it eliminates zero.
This function gives the right output:
def my_round(x, decimals):
str_decimals = str(x % int(x))
return str(int(x)) + str_decimals[1 : 2 + decimals]
What does my_round() do:
1- It retrieves decimals in a string format as a variable named str_decimals
2- Concatenates rounded int(x) with desired decimals and return as output.
Let's apply it:
Input
x = 7.00087
y = my_round(x, 3)
print(y)
Ouput
>>> 7.000

Printing binary without trailing 0s? [duplicate]

This question already has answers here:
Why does integer division yield a float instead of another integer?
(4 answers)
Closed 4 months ago.
Trying to create a small program that takes in positive integers and converts it into reverse binary.
I've gotten this far:
import math
integer = int(input())
while integer > 0:
x = integer % 2
print(int(math.floor(x)), end='')
integer = integer / 2
The problem with this is that the output would have unnecessary trailing 0s. For example, if the input is 12, the output would be 0011000......
I've tried the int function to remove floats, I also tried floor function to round up(albeit I might've done it wrong).
Could the problem be a lack of sentinel value?
It sounds like you have reversed a binary number like this:
def reverse_bits(n):
res = 0
for i in range(n.bit_length(), -1, -1):
if n & (1 << i):
res += 1 << (n.bit_length() - i)
return res
bin(reverse_bits(12)) # '0b110'
You can bit shift to the right, until there is a 1 in the rightmost bit, to remove trailing zeros:
def remove_trailing_zeros(n):
while not n & 1:
n = n >> 1
return n
All together:
bin(remove_trailing_zeros(reverse_bits(12)))
Out[11]: '0b11'
use // instead of / in division
Here is an alternate approach:
integer = 3
print (bin(integer)[2:][::-1])

Decimal to Binary number conversion program -- How to make it better or shroter? [duplicate]

This question already has answers here:
Python int to binary string?
(36 answers)
Closed 2 years ago.
I am a beginner in python. I have written a program to convert decimal numbers to binary. It works. But Is there any other way to make it better? Refer to my code. Thanks :)
def decimal_to_binary_converter(dec):
print(f"Decimal: {dec}")
binary = ""
# Using while loop dividing the decimal number by 2 and concatenating the reminder to the string variable "binary" .
# % Operator gets the reminder from the division.
while int(dec) > 0:
binary += str(int(dec)%2)
dec = int(dec) / 2
x = int(len(binary))
rev_binary = ""
# using this while loop reversing the string "binary" and showing the Output.
while x > 0:
rev_binary += str(binary[x-1])
x -= 1
return print(f"Binary: {rev_binary}")
decimal_to_binary_converter(945)
Output:
Decimal: 945
Binary: 1110110001
You can get it in one line
n = int(input())
binaryNo = bin(n).replace("0b","")

Converting a binary string to the equivalent base 10 value in python [duplicate]

This question already has answers here:
Convert base-2 binary number string to int
(10 answers)
Closed 7 years ago.
I want to convert a binary string (user input) to its base 10 equivalent value. I think I am somewhat close but just can't get it. This is what I have come up with so far. I need it to go through each individual number in the binary string and assign its base 10 equivalent value, then add all of those up for the entire base 10 number.
def getBaseTen(myString):
x = myString[0]
needAnswers = len(myString)
n = len(myString)
two = (2^n)
if (needAnswers >= 1):
return (int(x)*int(two))
The built-in int() can do this with an optional argument for the base:
>>> a = '11010'
>>> int(a)
11010
>>> int(a, 2)
26
Something like this: int(x, base=2) Link for more on this.
def getBaseTen(myString):
int(myString, 2)

How do remove trailing numbers in python [duplicate]

This question already has answers here:
Limiting floats to two decimal points
(35 answers)
Closed 8 years ago.
I am working on a python project and get a problem.
I have a for loop that makes a list with numbers. The problem is when I print out the list to check if the numbers are correct.
Some of the more simpler calculations are:
2.6 * 3 and 1.3 * 9
If you check with a calculator you should get 7.8 and 11.7, but I get 7.800000000000001 and 11.700000000000001
Which is not a big problem, but I don't like how it looks. (First world problem, I know)
Is there any way to fix it?
Use string format?
print "%.2f" % (2.6 * 3)
The %.2f means print a float to 2dp
You can use format to display the output you want:
>>> print(format(2.6 * 3, ".1f"))
7.8
Here ".1f" means "floating point number to one decimal place".
You can use format print.
res = 2.6*3
"%0.2f" % res
Here's a complete example with a list.
>>> n = [1.9, 7.8 , 9,3.4]
>>> print n
[1.8999999999999999, 7.7999999999999998, 9, 3.3999999999999999]
>>> twodecimals = ["%.2f" % v for v in n]
>>> print twodecimals
['1.90', '7.80', '9.00', '3.40']
>>> print twodecimals[0]
1.90
%.2f means prints only 2 decimal points. Similarly, .1f means 1 decimal point and so on.

Categories