Skip to content

Instantly share code, notes, and snippets.

@aasmpro
Last active March 24, 2022 22:02
Show Gist options
  • Save aasmpro/ae3dea0296f83d05276594dfb3a2a842 to your computer and use it in GitHub Desktop.
Save aasmpro/ae3dea0296f83d05276594dfb3a2a842 to your computer and use it in GitHub Desktop.
Python script to convert string to int without using built-in functions, and return the value with 3 fixed decimal places
import re
digits_dict = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
regex = "\s*(\+|\-)?\s*((\d)*(\.)?(\d)*)"
value = input()
result = re.search(regex, value)
sign = result.group(1) == '-' and -1 or 1
digits = result.group(2)
integer_value = 0
fraction_value = 0
decimal = False
fraction_counter = 1
for digit in digits:
if digit == '.':
decimal = True
continue
if decimal:
fraction_value = (fraction_value * 10) + digits_dict[digit]
fraction_counter *= 10
else:
integer_value = integer_value * 10 + digits_dict[digit]
if decimal:
integer_value = integer_value + ( fraction_value / fraction_counter )
print("{:.3f}".format(integer_value * sign))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment