I want to get up to the first digit other than 0 after the dot.
If there is a number other than 0 after the dot, it should be taken as 2 digits. So it must be sensitive.How do I do this with regular expressions or Python math library?
Here are examples
"0.00820289933" => "0.008"
"0.00000025252" => "0.0000002"
"0.858282815215" => "0.85"
"0.075787842545" => "0.07"
def format_adjusted_value(value):
str_value = str(value)
if '.' in str_value:
match = re.match(r'(\d*\.\d*?[1-9])0*$', str_value)
if match:
formatted_value = match.group(1)
else:
match = re.match(r'(\d*\.\d*?[0-9])0*$', str_value)
formatted_value = match.group(1) if match else str_value
else:
formatted_value = str_value
return formatted_value
>Solution :
Try like this
import re
def format_adjusted_value(value):
str_value = str(value)
match = re.match(r'\d*\.\d*?[1-9]', str_value)
formatted_value = match.group(0) if match else str_value
return formatted_value
test_values = [
"0.00820289933",
"0.00000025252",
"0.858282815215",
"0.075787842545",
]
for value in test_values:
print(f"{value} => {format_adjusted_value(value)}")
Output:
0.00820289933 => 0.008
0.00000025252 => 0.0000002
0.858282815215 => 0.8
0.075787842545 => 0.07