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