How to limit decimals without rounding

1

I have the following code, which is responsible for limiting the number of decimals of the result

a = 14567
n = "%.1f" % (a/1000)+"K")

at the time of doing print() , I get as a result 14.6K, the problem is that I do not want me to round it, I've already tried with the round function, but it gives me the same result.

I hope you can help me.

    
asked by OrlandoVC 28.11.2018 в 20:06
source

2 answers

2

From the format, I understand that there is no way, it will always round to the number of decimals you define. What is generally suggested is to build a routine to "truncate" directly the number of decimals you want:

import math

def trunc(f, n):
    return math.floor(f * 10 ** n) / 10 ** n

a = 14567
n = "%.1f" % trunc(a/1000,1) +"K"

print(n)

14.5K

But the other way is to directly cut the number already converted into a string

n = str(a/1000)
print(n[:n.index('.')+2] + "K")
14.5K
    
answered by 28.11.2018 / 20:21
source
2

The formatter %.1f uses round() to limit the number of decimals to the amount you request. This function admits a float (to be rounded) and an integer (number of decimals to be preserved). So basically, it will do round(x, 1) in this case.

round() uses as a rule to round the number to take the nearest number, with the number of decimal places requested. In your case, since the operation a/1000 results in 14.567 , you have to choose as a result of rounding 14.5 or 14.6 . The closest to the true value is 14.6 and that is therefore the answer.

Digression If both are equal distances (for example 14.550 is equal distance of 14.5 than 14.6 ) python uses a strange rule consisting of round to the one with the digit par . In this example, I would then round to 14.6 , that is, upwards. But following that same rule it turns out that 14.650 will also round to 14.6 , that is down . This strange behavior is little known, but it is correct because it is following a standard called round half to even , part of IEEE-754. However other languages do not do so, you must be overdrawn.

Going back to your question, although what you ask is a bit strange, the most flexible way to work with rounding is to use the decimal package. This package also avoids additional errors that can occur when operating with floating point, since in floating point the numbers are stored in binary, and when you divide by 10 or powers of 10 (as is usual in the metric system, or in finance ), since 10 is not power of 2, that produces errors.

For example, your operation 14567/1000 does not actually produce 14,567 as I said before, but 14.567000000000000170530256582424. What happens is that usually do not show so many decimals.

Using the decimal module the syntax becomes very cumbersome, but ensure that decimals and rounding are done correctly:

import decimal
a = Decimal(14567)
n = "%sK" % (a/1000).quantize(Decimal('1.1'), rounding=decimal.ROUND_FLOOR)
print(n)
14.5K
    
answered by 28.11.2018 в 20:34