If you want the result as the nearest binary floating point number use float:

result = [float(x.strip(' "')) for x in A1]

If you want the result stored exactly use Decimal instead of float:

from decimal import Decimal
result = [Decimal(x.strip(' "')) for x in A1]
Answer from Mark Byers on Stack Overflow
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › convert string to decimal in python
Convert String to Decimal in Python - Spark By {Examples}
May 21, 2024 - # Initialization the string string = "3.2583" # Use string formatting # Along with the float() function decimal_number = float(string) formatted_decimal = "{:.2f}".format(decimal_number) print("Original string:",string) print("After converting the string to decimal:",formatted_decimal) # Output: # Original string: 3.2583 # After converting the string to decimal: 3.26 · NumPy does indeed have a astype() method that can be used to convert the data type of a NumPy array. Here’s how you can use the astype() method to convert a string to a floating-point number in Python.
Discussions

python - How do I convert strings into decimal numbers? - Stack Overflow
If you are converting price (in string) to decimal price then.... from decimal import Decimal price = "14000.45" price_in_decimal = Decimal(price) ... In Python there are two floating point datatypes Float and Decimal. The use case depends on the precision of decimal you want in your program. More on stackoverflow.com
🌐 stackoverflow.com
c - conversion of string to decimal - Stack Overflow
I am using RS232 serial communication to rotate the motor. The serial communication is done in strings but i need decimal value for it. Any clues how to proceed.I am coding in c language.i tried us... More on stackoverflow.com
🌐 stackoverflow.com
Converting decimal strings to int
No you can't change the behaviour of int(). But in this case you can convert the string to float, then the float to int. More on reddit.com
🌐 r/learnpython
10
3
February 6, 2025
python - Character to decimal conversion - Code Review Stack Exchange
I've come to love the "straight-to-the-point" Python syntax a lot, and I embrace the delicious syntactic sugar of the language; but I keep seeing really bad naming of things among Python programmers. Maybe try this? def number_as_string_to_decimal(number_as_string): decimal = 0 base = ord('0') ... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
September 10, 2015
🌐
Python
docs.python.org › 3 › library › decimal.html
decimal — Decimal fixed-point and floating-point arithmetic
That is, while the coefficient is non-zero and a multiple of ten the coefficient is divided by ten and the exponent is incremented by 1. Otherwise (the coefficient is zero) the exponent is set to 0. In all cases the sign is unchanged. For example, Decimal('32.100') and Decimal('0.321000e+2') both normalize to the equivalent value Decimal('32.1'). Note that rounding is applied before reducing to simplest form. In the latest versions of the specification, this operation is also known as reduce. ... Return a string describing the class of the operand.
🌐
Techieclues
techieclues.com › blogs › how-to-convert-a-string-to-decimal-in-python
Convert a String to Decimal in Python
January 10, 2023 - float() in Python converts the string with numeric data into decimals.
Top answer
1 of 2
4

Use the strtoXXX() family of functions. If you need int, long or long long or their unsigned variants:

long l = strtol("1234567", NULL, 10);
long long ll = strtoll("1234567", NULL, 10);
unsigned long l = strtoul("1234567", NULL, 10);

If you need a float, double, or long double use this:

float f = strtof("3.1415927", NULL);
double d = strtod("3.1415927", NULL);

Manuals here and here.

2 of 2
1

Usually given a string:

char * myStr= "123";

the way to obtain it's value as an int is:

int value=atoi(myStr);

Some things important to notice:

the following include is necessary:

#include <stdlib.h>

and you must be sure that your string is a null terminated string otherwise atoi will crash you program.

You didn't gave us much information but if you're programming a microcontroller (I suspect that since you told us about a motor) you maybe won't want to use stdlib. In that case you might have use a costum function.

Please take a look at the code bellow:

int stringToInt(char* nrStr){
int nrChars=0;
while(nrStr[nrChars]!='\0'){
    nrChars++;
}


int result=0;
int i=0;
while(nrStr[i]!='\0'){//while you dont get to the end of the string
    int digit=nrStr[i]-48;//48 is zero ascii code
    int exp=nrChars-i-1;
    int add=digit*power(10,exp);
    result+=add;
    i++;


}
return result;


}
int power(int base, int exp){
int ret=1;
int i;
for(i=0;i<exp;i++){
    ret*=base;
}
return ret;
}

This does not use any library functions and does the job. I've done it in 3 minutes and it may have some small error, it's not very efficient and does not verify possible errors, but in principle if you pass the strinToint function a well formed integer as a null terminated string it will output the correct value.

If you're using a library that does have some implementation of a power function do use it instead of the one I gave you since it is not efficient at all.

One last note: if you for some reason need to use it in other basis lets say octal basis, you have to chance the line:

int add=digit*power(10,exp);

to:

 int add=digit*power(8,exp);

for hexadecimal this will not work, and implementation of such a function will be significantly different.

Find elsewhere
🌐
Online String Tools
onlinestringtools.com › convert-string-to-decimal
Convert a String to Decimal – Online String Tools
Simple, free and easy to use online tool that converts a string to decimal. No intrusive ads, popups or nonsense, just a string to decimal converter. Load a string, get a decimal.
🌐
Reddit
reddit.com › r/learnpython › converting decimal strings to int
r/learnpython on Reddit: Converting decimal strings to int
February 6, 2025 -

I'm trying to switch from pandas to polars and trying to be better about data types. If I try to cast int('3.4') it fails but I can execute int(float('3.4')). Is there a way to change this behavior so that the int casting performs the full conversion?

I'm primarily asking because polars is giving a read error in read_csv. I have created a data map dict with data types and column names but sometimes other people open and write the csv files in excel or something and 279 becomes 279.0 which polars refuses to read in as an int. Is there a way to force it to be an int?

🌐
W3Schools
w3schools.com › python › ref_string_isdecimal.asp
Python String isdecimal() Method
Remove List Duplicates Reverse ... Q&A Python Bootcamp Python Certificate Python Training ... The isdecimal() method returns True if all the characters are decimals ......
Top answer
1 of 4
6

You shouldn't use chr or str as names because they shadow the builtin chr and str methods. If you then wanted to use str() you'd be out of luck because str is now a string instead of a function. Given that your function deals with both strings and character ordinals it is not unlikely that these could be used. string is a potential improvement, it can occasionally cause trouble if you're trying to use the string module of the same name.

You should also add comments and a docstring. Docstrings are basically comments that are programmatically accessible so that other users can understand how to use your function.

def chrtodec(str):
    """Converts a string to a float using character ordinal positions."""

I think you have another big problem though, which is invalid input handling. Take a look at these:

>>> chrtodec("hello")
619663
>>> chrtodec("12.21")
11821
>>> chrtodec("523.32f")
5228374

Clearly there are problems here when you have characters other than numbers, so I think what you should do is raise a ValueError when an invalid string is passed. You already have the tools to do this figured out of course if you just check that a character's ordinal fits in the right range.

if not (ord('0') <= ord(chr) <= ord('9')):
    raise ValueError("Invalid character {} in string {},"
                     "only digits are parseable.".format(chr, str))

You could also just use chr.isdigit() as @Barry pointed out.

Also you could add support for negative numbers by checking at the start if the first character is ord('-').

negative = ord(str[0]) == ord('-')

This evaluates the expression str[0] == ord('-') and sets negative as the boolean result. Note that to make this compatible with the error handling I suggested, you should then remove the first character from str. And probably update the error message and docstring too.

if negative:
    str = str[1:]

Then just return with a ternary that checks negative.

return dec if not negative else -dec
2 of 4
3

Your code lacks modularization, This problem can be decomposed in:

  • Find the numerical value of a char.
  • Transform the chars into digits
  • Multiply all this numerical values by 10 ** position and sum them.

def char_to_integer(char):
    return ord(char) - ord('0')

The second function is an excellent place for a generator expression:

def string_to_digits(string):
    return (char_to_integer(i) for i in string)

Finally:

def digits_to_integer(digits):
    return sum(digit * 10 ** ( len(digits) - position )
        for position, digit in enumerate(digits))
🌐
freeCodeCamp
forum.freecodecamp.org › python
What is the best string to decimal code for floats i.e 0.5? - Python - The freeCodeCamp Forum
November 18, 2020 - Hello everyone, I have not been able to workout how to convert a string to a float. I’ve tried a.isdecimal() , a.isdigit() and a.isnumeric(). Please let me know if you have any advice. I’m asking for an input from 0 - …
🌐
Reddit
reddit.com › r/learnpython › convert fraction in string to a decimal
r/learnpython on Reddit: Convert fraction in string to a decimal
October 27, 2019 -

Is there any easy way to convert "3/4" to .75. Using float("3/4") doesn't work. Doing the following where fraction= "3/4" seems too complicated.

    fraction_answer = int(fraction.split("/")[0]) / int(fraction.split("/")[1])

Also what I'm really trying to do is convert something like "10 1/4" to 10.25

Edit: for people in the future i found for mixed numbers the following works well

    fraction_answer = eval(fraction.strip().replace(" ", "+"))
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python convert string to float
Python Convert String to Float - Spark By {Examples}
May 21, 2024 - If you are in a hurry, below quick examples will help you in understanding the different ways to convert a string to a float in Python. We will discuss them in detail with other important tips. # Quick examples of converting string to float # Method 1: Convert string to float using float() string_to_float = float("123.45") # Method 2: Convert string to float # Using the decimal module import decimal string_with_comma = "1,234.567" decimal_float = decimal.Decimal(string_with_comma.replace(',','')) # Method 3: Using regular expression import re pattern = r'^-?\d+\.\d+$' float_string = "123.45" m
🌐
Reddit
reddit.com › r/c_programming › how to convert a large decimal number in string form to base 2^16 in c?
r/C_Programming on Reddit: How to convert a large decimal number in string form to base 2^16 in C?
August 25, 2022 -

Hey everyone, I am currently trying to do some work with Big Numbers in C. Basically, I have an input of string digits in base 10 that is arbitrarily long (longer than long long int), and I am trying to store the data in an array of uint16_t types.

My original plan was to do atoi on individual digits, multiplying it by its location in the string (base 10), and adding it to the 0th value, and then managing overflows from there. So if it was 543, I would put the 3 in the first slot, then add 40 to make it 43 (check for overflow), then add 500 to make it 543 (check for overflow). If there were more numbers, I would keep going, and if there was any instance of overflow I would increment the next significant value by 1, check THAT for overflows, and keep going.

The problem is that when the numbers get really long, I can’t multiply the digit in the string by its place, as that is larger than INT_MAX, or even larger than long long int. How can I find which section of the uint16_t array to put the value to ensure no overflows, and allow me to keep cascading the “carry the 1” idea?

Alternatively, is there a flat out better way to do this? I have seen some stuff online about shortcuts you can take to convert an int to a base 2n, however I don’t think it works if the decimal is stored in string notation.

Top answer
1 of 2
7
Option 1: use a "big math" library. Option 2: roll your own basic addition routines, and build from there. Your big numbers will represented by a uint16_t[]. You add two base-N numbers by: adding the 1's column (potentially producing an overflow if the result exceeds N), then adding the N's column (potentially with the overflow from above, and potentially producing another overflow if the result exceeds N2) then adding the N2 's column, etc. etc. In your format, your 1's column is stored in array index [0], your N's columns is stored in [1], your N2 's column is stored in [2], etc. Adding two numbers So to add two uint16_t[] numbers, all you need to do is: add the two [0] values together, and if this exceeds your base (216) then you set an overflow flag, otherwise clear the overflow flag. add the two [1] values and the previous overflow together, and if this exceeds your base (216) then you set an overflow flag, otherwise clear the overflow flag. add the two [2] values and the previous overflow together, and if this exceeds your base (216)... ...etc. etc... eventually you run hit the end of the input arrays, and if the overflow is set then you need to extend the output array length by 1, and put the overflow there. Multiplying numbers Construct a lookup table, up to the maximum number of decimal digits you expect to handle. You can readily extend this to "arbitrary number of digits" but for now maybe cap it at 20 digits or so to prove the process. Construct a uint16_t[] number for "0" (your array is all zeros) Construct a uint16_t[] number for "1" (your array is all zeros, except for index [0] = 1) Save this in a lookup table at position [0] Construct a uint16_t[] number for "10" by adding your "1" to your "0" ten times. Save this in a lookup table at position [1] Construct a uint16_t[] number for "100" by adding your "10" to your "0" ten times. Save this in a lookup table at position [2] Construct a uint16_t[] number for "1000" by adding your "100" to your "0" ten times. Save this in a lookup table at position [4] Construct a uint16_t[] number for "10000" by adding your "1000" to your "0" ten times. Save this in a lookup table at position [4] ...etc. (Here you're obviously using your "add" routine that you wrote earlier! So now you have a lookup table of uint16_t[], where each subsequent index representing the next power of ten. Parse your base-10 text input Read your text input per-digit, 1's digit first, moving up through all the digits. Construct a uint16_t[] number for "0" (your array is all zeros). This will be your running sum that will eventually be your final output. read the 1's digit, and whatever its value is how many times you add to your running sum from position [0] of your lookup created in the "multiply" section above read the 10's digit, and whatever its value is how many times you add to your running sum from position [1] of your lookup created in the "multiply" section above read the 100's digit, and whatever its value is how many times you add to your running sum from position [2] of your lookup created in the "multiply" section above ... etc. (Again you're obviously using your "add" routine that you wrote earlier) Below 232, your uint16_t[] (if stacked end-on-end) should be bitwise identical to a uint32_t Below 264, your uint16_t[] (if stacked end-on-end) should be bitwise identical to a uint64_t
2 of 2
3
b * 10 equals (b * 2 * 2 + b) * 2. Maybe you can do with just longhand addition and a routine to shift left 1 bit.
🌐
Note.nkmk.me
note.nkmk.me › home › python
Convert a String to a Number (int, float) in Python | note.nkmk.me
April 29, 2025 - Format strings and numbers with format() in Python · You can also convert a list of strings to a list of numbers.
🌐
UiPath Community
forum.uipath.com › help › studio
How to convert String to Decimal ... to string again - Studio - UiPath Community Forum
March 25, 2024 - Hi to all, I have a problem managing the multiple conversion of a value, to convert to decimal, keeping the (.) decimal and the 2 decimal places, even if they are = 00 I’m working on a flow where, I collect data from a CSV and need to create an XML. I currently have a Read CSV and then an ...