Python 2.3: how can get exact float value after conversation? [duplicate] - python

This question already has answers here:
How to display a float with two decimal places?
(13 answers)
Closed 6 years ago.
x="1,234.00"
y =x.replace(',','')
k = float(y)
print k
output=1234.0 but i need 1234.00 value
please solve this problem

There is no difference in value between 1234.0 and 1234.00. You can't save more or less non-significant digits in a float.
However, you can print more or less (non-)significant digits. In older versions of python you can use the % method (documentation). In Python 2.7 and up, use the string format method. An example:
f = float('156.2')
# in Python 2.3
no_decimals = "%.0f" % f
print no_decimals # "156" (no decimal numbers)
five_decimals = "%.5f" % f
print five_decimals # "156.20000" (5 decimal numbers)
# in Python 2.7
no_decimals = "{:.0f}".format(f)
print no_decimals # "156" (no decimal numbers)
five_decimals = "{:.5f}".format(f)
print five_decimals # "156.20000" (5 decimal numbers)
If you for some reason have no access to the code that prints the value, you can create your own class, inherit from float and supply your own __str__ value. This could break some behaviour (it shouldn't, but it could), so be careful. Here is an example:
class my_float(float):
def __str__(self):
return "%.2f" % self
f = my_float(1234.0)
print f # "1234.00"
(I ran this on Python 2.7, I have 2.3 not installed; please consider upgrading Python to 2.7 or 3.5; 2.3 is seriously outdated.)

Related

how to print a float to 2 decimal places [duplicate]

This question already has answers here:
How to display a float with two decimal places?
(13 answers)
Closed 3 years ago.
I want number from input to print out with 2 decimal places. You can assume that the number will always be a float.
num = 20.0
Desired output - 20.00.
I've tried this code:
num = round(num, 2)
num = float('{0.2f}'.format(num))
print(num)
This should work
print('{0.2f}'.format(num))
When you turn this string back into a float with float() the formatting is lost.
No matter what you do to the float value, as long as it is still a float, it does not have any internal concept of decimal places.
If you want to display two decimal places, then that happens when you convert to text - which everything you print is, whether you asked for the conversion or not. You cannot make num "be" 20.00 as opposed to 20.0, because those aren't actually different things. (And keep in mind that the float simply cannot represent all decimal values exactly.)
Therefore, we use string formatting in the print call:
num = 20.0
print('{.2f}'.format(num))
# Or, using f-strings:
print(f'{num:.2f}')

Decimal part of a number in Python [duplicate]

This question already has answers here:
How can I force division to be floating point? Division keeps rounding down to 0?
(11 answers)
Closed 5 years ago.
I have the following program
def F_inf(a,b):
x1=a.numerator/a.denominator
x2=b.numerator/b.denominator
if x1<x2:
print "a<b"
elif x1>x2:
print "a>b"
else: print "a=b"
a=Fraction(10,4)
b=Fraction(10,4)
F_inf(a, b)
When I execute it,x1 receive just the integer value of the fraction, for exemple if I have to compute 2/4 x1 is equal to 0 not 0.5.
What should I do ?
Thanks
It sounds like you're using Python2. The best solution would be to switch to Python 3 (not just because of the division but because "Python 2.x is legacy, Python 3.x is the present and future of the language").
Other than that you have a couple of choices.
from __future__ import division
# include ^ as the first line in your file to use float division by default
or
a = 1
b = 2
c = a / (1.0*b) # multiplying by 1.0 forces the right side of the division to be a float
#c == 0.5 here

Ternary Conversion in Python not working well. Why? [duplicate]

This question already has answers here:
Convert decimal to ternary(base3) in python
(3 answers)
Closed 6 years ago.
I've tried to make a ternary calculator on Python, with some other functions like hex, bin, and oct with the built-in functions. There isn't one for ternary so I built one.
def ternary(n):
e = n/3
q = n%3
e = n/3
q = e%3
return q
i = int(input("May you please give me a number: "))
print("Binary "+bin(i))
print("Octal "+oct(i))
print("Hexadecimal "+hex(i))
print("Ternary "+ternary(i))
enter code here
But it doesn't work. Why? Where is the problem?
There are a couple of mistakes in your code which others have pointed out in the comments, but I'll reiterate them
You are using regular division when you want to use integer division (in Python 3).
You are returning an integer from your function whereas bin, oct, and hex all return strings.
In addition, your ternary function is incorrect, even with the errors fixed. The best way to write a function for base conversion on your own is with recursion.
def ternary(n):
if n == 0:
return ''
else:
e = n//3
q = n%3
return ternary(e) + str(q)

Binary in Python [duplicate]

This question already has answers here:
What do numbers starting with 0 mean in python?
(9 answers)
Closed 8 years ago.
When I write run the following code in Python:
m = 010001110110100101110110011001010010000001101101011001010010000001100001011011100010000001000001
print "m = ", m
I receive the output:
m = 7772840013437408857694157721741838884340237826753178459792706472536593002623651807233
What's happening? Is Python automatically converting from base 2 to base 10?
You're starting m with 0. Python assumes it's an Octal (see this)
What you're seeing is the decimal representation of the octal number.
If you want to work with that as binary numbers, I'd recommend setting it as an str and then parse it to int specifying that you're parsing something in base 2:
>>> m='0100011'
>>> int(m, 2)
35
Kind of, it interprets a number starting with 0 as octal, so it actually isn't binary in the first place.
In any case, you can make it output the integer as binary like so:
print "m = ", "{0:b}".format(m)

python round leaving a trailing 0 [duplicate]

This question already has answers here:
Most Pythonic way to print *at most* some number of decimal places [duplicate]
(3 answers)
Closed 9 years ago.
I am trying to round a floating point number in python to zero decimal places.
However, the round method is leaving a trailing 0 every time.
value = 10.01
rounded_value = round(value)
print rounded_value
results in 10.0 but I want 10
How can this be achieved? Converting to an int?
Pass the rounded value to int() to get rid of decimal digits:
>>> value = 10.01
>>> int(round(value))
10
>>> value = 10.55
>>> int(round(value))
11
10.0 and 10 are the same float value. When you print that value, you get the string 10.0, because that's the default string representation of the value. (The same string you get by calling str(10.0).)
If you want a non-default representation, you need to ask for it explicitly. For example, using the format function:
print format(rounded_value, '.0f')
Or, using the other formatting methods:
print '{:.0f}'.format(rounded_value)
print '%.0f' % (rounded_value,)
The full details for why you want '.0f' are described in the Format Specification Mini-Language, but intuitively: the f means you want fixed-point format (like 10.0 instead of, say, 1.0E2), and the .0 means you want no digits after the decimal point (like 10 instead of 10.0).
Meanwhile, if the only reason you rounded the value was for formatting… never do that. Leave the precision on the float, then trim it down in the formatting:
print format(value, '.0f')
Casting to an int would certainly be the easiest way. If you are hell-bent on keeping it a float here's how to do it courtesy of Alex Martelli:
print ('%f' % value).rstrip('0').rstrip('.')
You'll find a function number_shaver() that cuts trailing zeros of numbers in the EDIT 2 of this post.
Another post in the same thread explains how the regex in number_shaver() works.
I improved the regex in another thread some days later.

Categories