Convert Decimal Mark When Reading Numbers as Input

Convert decimal mark when reading numbers as input

float("2,5".replace(',', '.')) will do in most cases

If valueis a large number and .has been used for thousands, you can:

Replace all commas for points: value.replace(",", ".")

Remove all but the last point: value.replace(".", "", value.count(".") -1)

How can I get Python to recognize comma as the decimal point in user input?

You can use the replace method:

prvotna_cena = float(input('Prosim vnesi prvotno ceno:').replace(',','.'))

as.numeric with comma decimal separators?

as.numeric(sub(",", ".", Input, fixed = TRUE))

should work.

convert string to number without 'replace' Python

Use float regular expression to make sure, that you get the float number

txt = "77.4651 $"
x = float(re.search("[-+]?[0-9]*(?:\.?[0-9]*)[1]", txt).string)

or less safe split by spaces

float("77.4651 $".split("\s+")[0])

Reading Numbers (integers and decimals) from file w/period as delimiter

The %d conversion specification is for reading a decimal integer, and expects an int * argument. Similarly, the %i, %o, %u, %x and %X conversion specifications are also for integers.

Using %f is not going to work; it will read the 'second integer' as the fraction part of the first floating-point value, and there's no way to stop it doing that (unless you can safely use %3f because there'll always be at most 3 digits — which is a dubious proposition).

You'll need to use

int i1, i2;
if (fscanf(file, "%d.%d.%f", &i1, &i2, &tmp[2]) != 3)
{
…handle error…
}
tmp[0] = i1;
tmp[1] = i2;

This reads the integer values into int variables, then assigns the results to the float array elements. Note that you should always check the return value from fscanf() and friends. If it isn't what you expect, there's a problem (as long as your expectations are correct, which they will be once you've read the specification for fscanf() often enough — a couple of times a day for the first couple of days, once a day for the next week, once a week for the next month, and about once a month for the next year).



Related Topics



Leave a reply



Submit