Trimming arbitrary amount of zeroes [duplicate] - python

This question already has answers here:
Formatting floats without trailing zeros
(21 answers)
Closed 5 years ago.
I have a function which trims trailing decimal places from integers and converts it to a string. For example trim(1.0) outputs '1'.
this is my code:
def trim(num):
num1 = str(num)
try:
if '.0' in num1:
return num1[:num1:rfind('.0')]
return num1
except Exception:
pass
While this takes care of numbers with 1 trailing decimal places perfectly, it does not work with more decimal places (such as 2.000). Is there a way to trim all of the trailing decimal places?

First of all, you code is faulty. If I take your code and run this:
print(your_trim(1.1))
print(your_trim(1.0566))
print(your_trim('1cm'))
The output is:
1.1
1 <-- this is dangerous, the value is 1.0566!
1cm <-- this is not even a number
As the commenters mentioned, you may be mismatching floats and integers. As the name implies, an integer does not have decimal places. If your goal ist to strip trailing zeros (for whatever reason) and not round a float to an int, you might use something like this approach:
def strip_trailing_zeroes(num):
if isinstance(num, float):
if int(num) == num:
return int(num)
else:
return num
else:
raise ValueError("Parameter is not a float")
Testing the code:
print(strip_trailing_zeroes(1.1))
print(strip_trailing_zeroes(1.0566))
print(strip_trailing_zeroes(1.000))
print(strip_trailing_zeroes('1cm'))
Returns the output:
1.1
1.0566
1
Exception with "ValueError: Parameter is not a float"
As the other commenters put it, I can't imagine of a use case for this.
What you might be after, is trimming trailing zeros from a "string representation" of a float. For this, a simple regular expression replacement is enough:
# match a decimal point, followed by one or more zeros
# followed by the end of the input
print(re.sub('\.0+$', '', '2.000'))

Related

In Python, how can I get a whole number without decimals from math.sqrt?

import math
a = math.sqrt(25)
print(a)
My output is 5.0, how can I get a 5 (whole number) instead?
You have to check and explicitly convert to integer:
if x == (y := int(x)):
x = y
Or, without the assignment operator:
if x == int(x):
x = int(x)
As of python 3.8, you can use math.isqrt:
math.isqrt(25)
Keep in mind that this will always return an integer, even if the input is not a perfect square.
In a reduced manner, you can use a 1 line if operator to assign an integer value to the result of sqrt if both integer and decimal values are the same:
import math
a = math.sqrt(25)
a = int(a) if int(a)==a else a
print(a)
It depends a little on what exact behavior you want: do you want to just print the number without the decimal, or do you want to round a number to an integer?
For the print statement, Python tries to convert whatever is passed to it to a String in order to print it, and by default it gives floating point numbers decimal places. To stop that, we can use string formatting:
print("{:.0f}".format(a))
What this is doing is making a string (the double quotes "") that contains a special format marker (the curly braces {}). Inside the format marker is the code for the desired behavior (0 decimal places on a floating point number). Then we call the .format method of the string and pass the value (a) we want to be used inside the special format marker.
This looks somewhat arcane and ugly, but is the safest method to print what you want because it does not change 'a' and is easily customizable to other printing behaviors.
For rounding a number and converting it to an int, you can either use int() or round(): both will take in a float and output an integer that will print cleanly (and be an integer for future computation). There is no requirement for the thing being converted to actually be an integer but there is different behavior for the two functions: int returns the value of the first digit of a number, while round returns the rounded value (IE round(1.9) -> 2, int(1.9) -> 1, etc).

In python, i want to thousands separate decimal numbers and display with exactly 2 decimal digits

Consider the following numbers:
1000.10
1000.11
1000.113
I would like to get these to print out in python as:
1,000.10
1,000.11
1,000.11
The following transformations almost do this, except that whenever the second digit to the right of the decimal point is a zero, the zero is elided and as a result that number doesn't line up properly.
This is my attempt:
for n in [1000.10, 1000.11, 1000.112]:
nf = '%.2f' %n # nf is a 2 digit decimal number, but a string
nff = float(nf) # nff is a float which the next transformation needs
n_comma = f'{nff:,}' # this puts the commas in
print('%10s' %n_comma)
1,000.1
1,000.11
1,000.11
Is there a way to avoid eliding the ending zero in the first number?
You want the format specifier ',.2f'. ,, as you noted, performs comma separation of thousands, while .2f specifies that two digits are to be retained:
print([f'{number:,.2f}' for number in n])
Output:
['1,000.10', '1,000.11', '1,000.11']
You can simply use f'{n:,.2f}' to combine the thusand separator and the 2 decimal digits format specifiers:
for n in [1000.10, 1000.11, 1000.112]:
print(f'{n:,.2f}')
Outputs
1,000.10
1,000.11
1,000.11
You might be able to do it like this:
num = 100.0
print(str(num) + "0")
So you print the number as a string plus 0 at the end.
Update:
So that it doesn’t do this to all numbers, try doing something like:
if num == 1000.10:
#add the zero
elif num == 1000.20:
#again, add the zero
#and so on and so on...
So if the number has a zero at the end (its decimal values are .10, .20, .30, etc.), add one, and if not, don’t.

python float is not digit? [duplicate]

This question already has answers here:
How to check if a user input is a float
(6 answers)
Closed 4 years ago.
This code returns False, but when I delete point from float it becomes True and I'm trying to understand why. Explain please
def isDigit(string):
string = string.strip()
if string[:1] == "-":
cuted = string[1:]
if cuted.isdigit():
return True
else:
return False
elif string.isdigit():
return True
else:
return False
print isDigit("-234.4")
also I know my code is not the best and I wonder how can I make it better
isdigit only checks if all the characters are digits (e.g. 0, 1, ... 9).
Therefore the string 234.4 will return False because it also contains a decimal point ., that is not a digit.
help("".isdigit)
will tell you that to be True all characters must be digits and there must be at least one character.
You could use a regular expression to do this kind of checking, for example with something like:
import re
def isnumber(x):
return re.match("-?[0-9]+([.][0-9]+)?$", x) is not None
that will accept an optional minus sign, followed by a sequence of one or more digits optionally followed by a decimal dot and more digits.
Note that floating point numbers can be accepted by a much wider syntax, including scale exponent and missing parts before and after the decimal point so don't be this strict if you're validating output from a computer. Depending on the context it may be however meaningful to refuse things like 1e4 as numbers from a human.
Let's step through your code.
if string[:1] == "-":
string[:1] means "make a string with characters from the start of string up to (but not including) index 1." If your string is "foobar", string[:1] will be "f". In your example, string[:1] will be "-"
cuted = string[1:]
This will do the opposite, producing a string that contains everything but the first character. In this case, cuted would be "234.4"
if cuted.isdigit():
return True
else:
return False
This will test if cuted is made up only of numbers. In our case, this is false, because it contains a decimal point. False is returned.
elif string.isdigit():
return True
else:
return False
If the first character was not "-", this is run instead. If you supplied "234.4", this case would be reached, and the test would fail (because "234.4" contains a decimal point), so False would be returned.
Your code appears to be valid if what you wanted was:
123.3 -> False
-123.3 -> False
123 -> True
-123 -> True
On the other hand, if you want your function to say all four of those are numbers, then you need to modify your code. The one way (probably not the best!) to do that would be to have a test case that does something like this:
If I split this string on ".", do I get two strings?
If so, are both pieces of the string digits?
If so, the string is a number.
It's not clear exactly what behavior you want.

Python convert int to string preserving zeros [duplicate]

This question already has answers here:
How do I pad a string with zeroes?
(19 answers)
Closed 6 years ago.
i'd like to convert a decimal to a string, where zeros at the end are preserved.
Using str method erases the last zeros.
Example:
number=0.20
Goal: "0.20"
e.g. using: str(number)="0.2" doesn't seem to work.
If you want 2 decimal places use:
number = 0.20
str_number = '%.2f' % number
Number before f indicates the desired number of places.
This can be done using string formatting.
"{0:.2f}".format(number)
Will return 0.20.
Doing your chosen method won't work because upon declaring number = 0.20 it omits the last zero right away. If you put that into your idle:
number = 0.20
number
0.2
So declaring number as str(number) is doing str(0.2).
Use the % operator with an appropriate format string:
'%1.2f' % number
=> '0.20'

How can I check if a string has a numeric value in it in Python? [duplicate]

This question already has answers here:
How do I check if a string represents a number (float or int)?
(39 answers)
Closed 7 months ago.
For example, I want to check a string and if it is not convertible to integer(with int()), how can I detect that?
Use the .isdigit() method:
>>> '123'.isdigit()
True
>>> '1a23'.isdigit()
False
Quoting the documentation:
Return true if all characters in the string are digits and there is at least one character, false otherwise.
For unicode strings or Python 3 strings, you'll need to use a more precise definition and use the unicode.isdecimal() / str.isdecimal() instead; not all Unicode digits are interpretable as decimal numbers. U+00B2 SUPERSCRIPT 2 is a digit, but not a decimal, for example.
You can always try it:
try:
a = int(yourstring)
except ValueError:
print "can't convert"
Note that this method outshines isdigit if you want to know if you can convert a string to a floating point number using float

Categories

Resources