HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonModerate

Safely convert dollars to cents

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
convertsafelycentsdollars

Problem

For my project, I need to convert dollar to cents, so I wrote the following function to safely do the conversion. The input dollar is float and the output should be int.

def safe_dollar_to_cent(dollar):
    parts = str(dollar).split('.')

    msg = 'success'
    status = 0
    if len(parts) == 1:
        return status, int(parts[0])*100, msg

    decimal_part = parts[1]
    if len(decimal_part) > 2:
        decimal_part = decimal_part[0:2]
        msg = 'dollar has been truncated: {} -> {}'.\
              format(parts[1], decimal_part)
        status = 1

    ret = int(parts[0]) * 100
    multiplier = 10
    for i, s in enumerate(decimal_part):
        ret += int(s) * multiplier
        multiplier /= 10

    return status, ret, msg


I am posting here for seeking other some pythonic way of doing this job.

Update:

my input is expected to be float, the return value should be int.
The reason of this implementation is that I found the following incorrect computation.


18.90 * 100 = 1889.9999999999998

Solution

I don't like the 3 argument return you're doing. You're using status and msg to actually do the same thing. They both return a signal of success unless the dollar is truncated. You don't need both pieces of information. Personally, I'd just say that you only need to print a note about the dollar being truncated so that the function only returns the cents value.

Now, you're also overlooking a very simple formula to convert this:

cents = dollars * 100


You don't need anything more complicated than that for the basic function:

def safe_dollar_to_cent(dollar):
    cents = dollar * 100
    return cents


If you're not sure that dollar will be a number, you can try converting it:

def safe_dollar_to_cent(dollar):
    cents = float(dollar) * 100
    return cents


As for truncating, I think it's better as an option. Let the user choose whether or not something will be truncated:

def safe_dollar_to_cent(dollar, truncate=True):
    cents = float(dollar) * 100
    if truncate:
        return int(cents)
    else:
        return cents


int will turn cents into a whole number instead of a decimal, so it's effectively truncating everything after the ..

Code Snippets

cents = dollars * 100
def safe_dollar_to_cent(dollar):
    cents = dollar * 100
    return cents
def safe_dollar_to_cent(dollar):
    cents = float(dollar) * 100
    return cents
def safe_dollar_to_cent(dollar, truncate=True):
    cents = float(dollar) * 100
    if truncate:
        return int(cents)
    else:
        return cents

Context

StackExchange Code Review Q#121074, answer score: 12

Revisions (0)

No revisions yet.