0

anyone know how f-string roundup work, I want to around to decimal 2 position but I found out f-string does not round up for decimal 2 position

>>> a = 0.1235
>>> f'{a:.3f}'
'0.124' #as expect
>>> a = 0.125
>>> f'{a:.2f}'
'0.12' # why not 0.13?
>>>
jacobcan118
  • 7,797
  • 12
  • 50
  • 95
  • 2
    I am getting `0.123` from the first example (using Python 3.7.4), as I would have expected. I believe it just truncates to the desired length. – StardustGogeta Jul 24 '19 at 15:01
  • 1
    see also https://docs.python.org/3/tutorial/floatingpoint.html – Sam Mason Jul 24 '19 at 15:02
  • note that 0.1235 can't be represented in a float, it's actually slightly smaller (try `decimal.Decimal(0.1235)`) and hence it rounds down. not sure what's going on with 0.125 though, it can be represented correctly – Sam Mason Jul 24 '19 at 15:08
  • i am using Python 3.6.4 – jacobcan118 Jul 24 '19 at 15:11
  • In Python 3.6.5: `f'{.1235:.3f}'` gives `.123` – Checkmate Jul 24 '19 at 15:12
  • @SamMason any reason 0.1235 can't be in a float? – jacobcan118 Jul 24 '19 at 15:12
  • @Checkmate yes, but my question is f'{.1235:.3f}' why it is not .124? – jacobcan118 Jul 24 '19 at 15:13
  • 1
    @jacobcan118 The difference here is floating-point representations. `.1235` can't be represented exactly, since it's not a power of 2. As a result, there is some rounding error, which could lead to this number being rounded up (which is not the intended behavior) – Checkmate Jul 24 '19 at 15:15
  • Even `round(0.125,2)` gives you `0.12` so not sure what you are comparing against – Devesh Kumar Singh Jul 24 '19 at 15:17
  • got it, so how should we do round for the value not power of 2 or avoid this type of rounding error? – jacobcan118 Jul 24 '19 at 15:25
  • @jacobcan118 The more general principle is not to trust that decimals are exact. `.1235` might be `.123500001` internally, it might be `.1234999999`, you just don't know for a given value without careful testing. So just don't assume that exact rounding will behave as you expect in all cases. If you really want to deal with exact cases, then study floating-point representation (linked above) in greater detail. – Checkmate Jul 24 '19 at 15:35
  • @jacobcan118 your examples are caused by different things. 0.125 is caused by "round to even" behaviour, while 0.1235 can't be represented accurately – Sam Mason Jul 24 '19 at 15:42

0 Answers0