Convert String to Negative Number

Convert a string to an int with negative numbers

I've already done this successfully (with positive) with this code:

Good. An important insight is to build on success.

As int charTOint(char * c) { works well with positive values, perhaps re-write it using unsigned. We get more range as UINT_MAX is typically greater than INT_MAX.

unsigned charTOunsigned(const char * c) {
char p = *c;
unsigned ergebnis = 0;
while (p) {
ergebnis = ergebnis * 10 + (p - '0');
c++;
p = *c;
}
return ergebnis;
}

I need it to also work with negative numbers / char arrays starting with a '-'.

Now armed with charTOunsigned(), use that variation of good existing code to re-make a int charTOint() that meets the additional goal. With the usual extra positive range of charTOunsigned(), int charTOint() will readily handle a string that converts to INT_MIN.

int charTOint(const char * c) {
return (*c == '-') ? -charTOunsigned(c+ 1) : charTOunsigned(c);
}

Certainly one could code a stand-alone charTOint(), yet I wanted to emphasize code re-use. That makes for a productive coder.

Convert negative number in string to negative decimal in JavaScript

The parseInt function can be used to parse strings to integers and uses this format: parseInt(string, radix);

Ex: parseInt("-10.465", 10); returns -10

To parse floating point numbers, you use parseFloat, formatted like parseFloat(string)

Ex: parseFloat("-10.465"); returns -10.465

Converting a string with negative numbers into list of float

With your sample data:

with open('Input_file.txt') as f:
for line in f:
data = [float(n) for n in line.split()]
print(data)

Output:

[0.0, 8.42, 43.0, -1.5]
[-259.0, 0.832]
[522.0, -32.0]
[-3.33]
[12.0, -3.0, -45.0]

Converting a String with negative numbers and decimals into an int?

"-106.55" is not an int, it's a double. Use Double to parse it:

double d = Double.parseDouble(String a);

If you want to keep an int portion of it, use a cast:

int n = (int)d;

How to convert strings with positive/negative integers and floats in Python

Cause:

'+' and '-' are not is_numeric() - you need to handle those manually if you want to keep your approach.

See farther down for a shorter and better way to do the same thing.

Fix:

def convert_data(data: List[List[str]]) -> None:
for sublist in data: #Accesses each element in data
for index, element in enumerate(sublist):
sign = 1
# parse sign for later multiplication
if element.startswith("+"):
element = element[1:]
elif element.startswith("-"):
sign = -1
element = element[1:]

if element.isnumeric(): # '12345'
sublist[index] = sign * int(element)

elif element.replace('.', '').isnumeric(): # '123.45' but also '12.3.2020'
sublist[index] = sign * float(element) # convert to a float

else:
sublist[index] = sublist[index] # keep as is

our_data = [['no'], ['-123'], ['+5.6', '3.2'], ['3.0', '+4', '-5.0']]
convert_data(our_data)
print(our_data)

Output:

[['no'], [-123], [5.6, 3.2], [3.0, 4, -5.0]]

Optimization and more pythonic:

def convert_data(data )  :
for sublist in data:
for index, element in enumerate(sublist):
try:
element = float(element)
if element.is_integer():
element = int(element)
except ValueError:
pass
sublist[index] = element

See "Ask forgiveness not permission" - explain



Related Topics



Leave a reply



Submit