0

Okay am I going crazy? Run the code below, instead of being 3480 it says 3479, is this a bug? every other number works fine

def validate_dollar(dollar):
    return dollar * 100 % 1 == 0

def safe_dollar_to_cent(dollar):
    if validate_dollar(dollar):
        return {'success': True, 'cents': int(dollar*100)}
    else:
        return {'success': False, 'msg': 'Malformed input'}

print(safe_dollar_to_cent(34.8))

print(int(34.8 * 100))
  • Looks like floating point precision issues. https://stackoverflow.com/questions/588004/is-floating-point-math-broken is highly relevant. – Nathan Pierson Sep 13 '20 at 06:30
  • Interesting thank you – givob88903 Sep 13 '20 at 06:30
  • 1
    And also don't use floats to represent amount of money: https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency – awesoon Sep 13 '20 at 06:35
  • `x % 1 == 0` is always true – goodvibration Sep 13 '20 at 06:44
  • @goodvibration That's true when `x` is an integer, not true when `x` can be a float. The idea of the code being that `34.80` should be a valid amount but `34.8001` should not is reasonable. It just happens to be right along a floating precision faultline. – Nathan Pierson Sep 13 '20 at 06:48
  • Use the [decimal module](https://docs.python.org/3/library/decimal.html) for money, or work only with cents, only converting to dollars for display to the user. – snakecharmerb Sep 13 '20 at 07:55

2 Answers2

0

change int !! write float instead int int the line number 10 !

0
def validate_dollar(dollar):
     return dollar * 100 % 1 == 0

def safe_dollar_to_cent(dollar):
    if validate_dollar(dollar):
        return {'success': True, 'cents': int(dollar*100)}
    else:
        return {'success': False, 'msg': 'Malformed input'}

print(safe_dollar_to_cent(34.8))

print(round(34.8 * 100))
Juhi Dhameliya
  • 170
  • 2
  • 9