How to fix the number of numeric characters of a float?

4

I wrote a simple code where at the end of a mathematical operation I need the result to come out with seven numeric characters regardless of where the dot is. Unfortunately I can only adjust the precision of the decimal places but I need something like this: 10.0000 or 1000.01 or 0.00007 the "size" of the number must always be truncated with 7 characters. For example, for the result: -3.1700000000419095 0.0 0.0 I need to adjust to: -3.1700 0.00000 0.00000

    
asked by anonymous 12.06.2017 / 23:45

5 answers

3

Only you set the output of it to seven decimal places, so regardless of the number will be shown the amount set after . , however, to control that the seven numeric characters is always shown regardless of the response, is not very usual .

For example:

a = -3.1700000000419095
b = 0

print('{0:.7f}'.format(a))

print('{0:.7f}'.format(b))
When we make a print by putting a {} means that we leave that place reserved to make an impression of some value to be passed, I used the {0:.7f} to set seven digits to the right of the number, independent number of the size still do not know how to do. And then, we use .format() to display the variable that will be used for formatting.

As a result of the code above, I get:

-3.1700000
0.0000000
    
03.11.2017 / 20:23
1

Use the basics: "{0:. number of decimal places f}" format ( number )

>>>"{0:.2f}".format(1/7)
>>>'0,14'
>>>
>>>"{0:.5f}".format(1/2)
>>>'0.50000'
    
26.02.2018 / 02:25
0

Transforms into a string and then trims it. If the number is smaller than the size you want, fill in with leading zeros:

def numero_sete(numero):
    numero = float(numero)
    numero = str(numero)
    numero = numero[:7]
    numero = numero.ljust(7, '0')

    return numero

numero_sete(-3.1700000000419095)
'-3.1700'
numero_sete(0.01)
'0.01000'
    
13.06.2017 / 00:00
0
def trunca_sete(num):
    return '%.7s' % (str(num).ljust(7, '0'))

trunca_sete(-3.1700000000419095)
'-3.1700'
trunca_sete(0.0)
'0.00000'
trunca_sete(1000.01)
'1000.01'
trunca_sete(1000.0199999)
'1000.01'
    
14.06.2017 / 14:49
0

TL; DR

You can do this by calculating the size of the unit part, whether it is negative or not, and then round the number according to the previous numbers.

def num_to_7_char(num):
    if num == 0:
        return "0.00000"

    int_part = int(log10(abs(num))) + 1
    minus_part = int(num < 0)
    round_to = max(6 - int_part - minus_part, 0)

    return "{num:.{round_to}f}".format(num=num, round_to=round_to)

Code working in Repl.it

Explanation

If the number is zero, it returns 0.00000 because a logarithm of 0 can not be calculated.

To calculate the unit part of the number I use the method math.log10 to know how many houses the number has, calculating how many times I have to multiply the number 10 to reach the desired number. Ex.:

from math import log10

print(log10(1))    # 0
print(log10(10))   # 1
print(log10(100))  # 2

I use the abs method to get the module of a number, because to calculate a logarithm the number must be greater than 0.

I use int to convert the result to an integer and sum 1 so that the number of unit digits of the number.

To compute the space that will be occupied by the character - (minus sign) I make a simple boolean to integer conversion, where True will become 1 and False will become 0 .

The variable round_to stores the amount we want in decimal places, as this will depend on how many characters will be to the left of the point.

The rounding calculation is done by decreasing the whole part and the part of the signal of the desired total. In this case the desired total is 6, as it is necessary to consider that the point will occupy a character.

max is being used so that round_to is not negative , it sets the minimum threshold to zero. Ex.:

max(1, 0)  # 1
max(0, 0)  # 0
max(-1, 0) # 0

At the end formatting strings is used using the str.format to round and limit the number. The PyFormat site has good examples to understand how it works.

See that this template does not work correctly in some cases for obvious reasons certain numbers are not possible to be represented in 7 characters without specifying some other rules, for example:

  • Number greater than 9_999_999 : it would take at least 8 characters to represent them.
  • 6-digit integers: The algorithm uses the rule to convert a int to float and fill in the remaining characters with zeros on the right, but if an integer has only 6 digits it can not be represented as just add one point, without being able to add zeros.
27.12.2018 / 15:01