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 Overflowpython - How do I convert strings into decimal numbers? - Stack Overflow
c - conversion of string to decimal - Stack Overflow
Converting decimal strings to int
python - Character to decimal conversion - Code Review Stack Exchange
Videos
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]
If you are converting price (in string) to decimal price then....
from decimal import Decimal
price = "14000.45"
price_in_decimal = Decimal(price)
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.
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.
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?
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
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))
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(" ", "+"))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.
If you want to stay in decimal numbers, safest is to convert everything:
>>> s = '23.456'
>>> d = decimal.Decimal(s)
>>> d - decimal.Decimal('1')
Decimal('22.456')
>>> d - decimal.Decimal('1.0')
Decimal('22.456')
In Python 2.7, there's an implicit conversion for integers, but not floats.
>>> d - 1
Decimal('22.456')
>>> d - 1.0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'Decimal' and 'float'
Is the Decimal required for your computations? The Decimal fixed point and floating point arithmetic doc outlines their differences. If not, you could just do
d = float('23.456')
d
23.456
d - 1
22.456
Oddly enough re Decimal, I get this interactively
d = decimal.Decimal('23.456')
d
Decimal('23.456')
d - 1
Decimal('22.456')
But when I print it, I get the values
print d
23.456
print d-1
22.456
I'm trying to convert the strings in this... array of arrays (?) into decimal form:
ask = [['31188.28758860', 2], ['31183.48445986', 0.14258435], ...]
I tried using elem.strip('"') for elem in ask to remove the quote marks but get "AttributeError: 'list' object has no attribute 'strip'" So I assume I am not accessing the nested level of the strings
You're right, Elem is a list because you have a list of lists. A nice way to achieve this is with unpacking:
for x, y in ask:
print(float(x))
I imagine you'll want to store this in a new list which you'd need to add a bit more code for. This also looks like something you could use a 'list comprehension' for.
If you know the structure is always a list of lists, then you could do something like this:
ask_float = [list(map(float, a)) for a in ask]
This would use a list comprehension to iterate over the lists and map the float() function to every list in the list, then convert the map back to a list and put in in the outer list.