PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 10, 2022

[FIXED] How does Python babel round numbers?

 August 10, 2022     currency, decimal, python, python-babel, rounding     No comments   

Issue

I'm building a financial website with the Flask framework and I'm currently writing unit tests for it. I'm using the Babel package to format money amounts and I hit upon rather strange rounding behaviour. I would expect rounding to be up in case of a 5, or to at least be consistent. But look at this:

>>> from decimal import Decimal
>>> from babel.numbers import format_currency
>>> print format_currency(Decimal('.235'), 'EUR', locale='nl_NL')
€ 0,24
>>> print format_currency(Decimal('.245'), 'EUR', locale='nl_NL')
€ 0,24

Why is this so, and more importantly; how can I solve this?

ps: I would prefer .245 to be rounded up to .25

[EDIT]

I went looking for the source, which links to some other pieces of code. But I can't really figure out what's wrong there and why it seems to randomly round up or down. Anybody any idea?


Solution

If you follow the code through to apply you can see a reference to a bankersround procedure, which tells us what we need to know. Babel is using the bankers round method of rounding, which rounds to the nearest even number on 5. So, .245 and .235 round to .24 as .24 is the closest even value for each. Values above and below 5 round normally.



Answered By - paidhima
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing