Easy way of finding decimal places

PythonStringDecimal

Python Problem Overview


Is there an easy way or integrated function to find out the decimal places of a floating point number?

The number is parsed from a string, so one way is to count the digits after the . sign, but that looks quite clumsy to me. Is there a possibility to get the information needed out of a float or Decimal object?

Python Solutions


Solution 1 - Python

To repeat what others have said (because I had already typed it out!), I'm not even sure such a value would be meaningful in the case of a floating point number, because of the difference between the decimal and binary representation; often a number representable by a finite number of decimal digits will have only an infinite-digit representation in binary.

In the case of a decimal.Decimal object, you can retrieve the exponent using the as_tuple method, which returns a namedtuple with sign, digits, and exponent attributes:

>>> d = decimal.Decimal('56.4325')
>>> d.as_tuple().exponent
-4
>>> d = decimal.Decimal('56.43256436')
>>> d.as_tuple().exponent
-8

The negation of the exponent is the number of digits after the decimal point, unless the exponent is greater than 0.

Solution 2 - Python

"the number of decimal places" is not a property a floating point number has, because of the way they are stored and handled internally.

You can get as many decimal places as you like from a floating point number. The question is how much accuracy you want. When converting a floating point number to a string, part of the process is deciding on the accuracy.

Try for instance:

1.1 - int(1.1)

And you will see that the answer is:

0.10000000000000009

So, for this case, the number of decimals is 17. This is probably not the number you are looking for.

You can, however, round the number to a certain number of decimals with "round":

round(3.1415 - int(3.1415), 3)

For this case, the number of decimals is cut to 3.

You can't get "the number of decimals from a float", but you can decide the accuracy and how many you want.

Converting a float to a string is one way of making such a decision.

Solution 3 - Python

The fastest way I found for calc digits after decimal point and rounding the number is

Calculate digits:

a=decimal.Decimal('56.9554362669143476');
lenstr = len(str(a).split(".")[1])

Calc, check and rounding:

a=decimal.Decimal('56.9554362669143476');
a = round(float(a),5) if len(str(a).split(".")[1]) > 5 else float(a)

Comparison:

$ python2 -mtimeit 'import decimal; a=decimal.Decimal('56.9554362669143476'); round(float(a),5) if a.as_tuple().exponent < -5 else float(a)'
10000 loops, best of 3: 32.4 usec per loop
$ python -mtimeit 'import decimal; a=decimal.Decimal('56.9554362669143476'); a = round(float(a),5) if len(str(a).split(".")[1]) > 5 else float(a)'
100000 loops, best of 3: 16.7 usec per loop

Solution 4 - Python

In case you only need to find the decimal place of the most significant digit, ie. the leftmost one, another primitive solution would be:

fraction = 0.001
decimal_places = int(f'{fraction:e}'.split('e')[-1])

This makes use of the scientific notation (m x 10^n), which already provides the number of decimal places in form of the power (n) of 10, to which the coefficient (m) is raised, ie. -3, derived from 1.000000e-03 for the above example.

An important difference to Decimal(str(fraction)).as_tuple().exponent is that the scientific notation will always only consider the most significant digit for the exponent n, similar to Decimal().adjusted(), whereas Decimal().as_tuple().exponent returns the exponent of the least significant digit.

String formatting to scientific notation can of course also only handle floats and no strings, thus any floating point arithmetic issues persist. However, for many use cases the above might be sufficient.

Solution 5 - Python

The decimal library is for working with decimal numbers, like in Accounting. It doesn't inherently have a function to return the number of decimal places. This is especially a problem when you realize that the context it runs under sets it at whatever the user wants.

If you get a string, you can convert to decimal, but this will either tack on zeros to get you to your accuracy, or use the rounding setting to truncate it.

Your best bet would probably bet splitting on the dot in your string and counting the number of chars in the resulting substring.

Solution 6 - Python

I needed something like this and i tested some of these, the fastest i found out was :

str(number)[::-1].find('.')

Because of the floating point issue all the modulo ones gave me false results even with Decimal(number) (note that i needed this in a script to fix prices of an entire db)

len(str(Decimal(str(number))) % Decimal(1))) - 2

The need to put a string into Decimal is quite uneasy when we have floats or something like.

Here is my "bench" : https://repl.it/FM8m/17

Solution 7 - Python

If you know you're not going to have parsing issues (or if you're letting python itself or some other library handle that for you, hopefully handling localization issues)... just parse it and use modf. The return value is a pair of values, one of which is the integral part, the other is the fractional part.

Solution 8 - Python

Since Python floating point numbers are internally represented as binary rather than decimal, there's really no shortcut other than converting to decimal. The only built-in way to do that is by converting to a string. You could write your own code to do a decimal conversion and count the digits, but it would be a duplication of effort.

Solution 9 - Python

This worked for me:

import decimal   

def HowManyDecimals(decimal_number):
        if not type(decimal_number) == "decimal.Decimal":
            return "ERROR"
        if not str(decimal_number).find(".") == -1:
            decimals = len(str(decimal_number).split(".")[1])
        else:
            decimals = 0
        return decimals

a_decimal = decimal.Decimal("1.12345678901234567890123")
print(HowManyDecimals(a_decimal))

Solution 10 - Python

    from math import log10
    my_number = 3.1415927

    int(log10(float(str(my_number)[::-1])))+1

The way it works is that log10(number)+1 will give us the number of digits to the LEFT of the decimal place.

If we were to REVERSE the digits then the digits on the left would have previously been on the RIGHT.

    # Reverse the string
    any_string[::-1]

Solution 11 - Python

Here's what worked for me:

string_value = "1234.1111"
exponent = (-len(string_value.rpartition(".")[-1])
            if "." in citem.toll_free_pricing else 0)
print(exponent)
# prints "-4"


string_value = "1234"
exponent = (-len(string_value.rpartition(".")[-1])
            if "." in citem.toll_free_pricing else 0)
print(exponent)
# prints "0"

Here's how the code is "broken-down":

string_value = "1234.1111"

if "." in citem.toll_free_pricing:

    tuple_value = string_value.rpartition(".")
    print(tuple_value)
    # prints "('1234', '.', '1111')"

    decimals = tuple_value[-1]
    print(decimals)
    # prints "1111"

    decimal_count = len(decimals)
    print(decimal_count)
    # prints "4"

    exponent = -decimal_count
    print(exponent)
    # prints "-4"

else:
    print(0)

Solution 12 - Python

x = 1.2345

x_string = (str(x))

x_string_split = x_string.split('.')

x_string_split_decimal = x_string_split[1]

print(x_string_split_decimal)

print(len(x_string_split_decimal))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionConstantiniusView Question on Stackoverflow
Solution 1 - PythonsenderleView Answer on Stackoverflow
Solution 2 - PythonAlexanderView Answer on Stackoverflow
Solution 3 - PythonGeorgeView Answer on Stackoverflow
Solution 4 - PythonmawallView Answer on Stackoverflow
Solution 5 - PythonSpencer RathbunView Answer on Stackoverflow
Solution 6 - PythonJérémy JOKEView Answer on Stackoverflow
Solution 7 - PythonjkerianView Answer on Stackoverflow
Solution 8 - PythonMark RansomView Answer on Stackoverflow
Solution 9 - PythonSalu RamosView Answer on Stackoverflow
Solution 10 - Pythonuser3535147View Answer on Stackoverflow
Solution 11 - Pythonnicolas.leblancView Answer on Stackoverflow
Solution 12 - PythonGaneshView Answer on Stackoverflow