For mine project, I require to transform dollar to cents, therefore I wrote the following role to safely perform the conversion. The input disagreement is float and the output need to be int.

You are watching: How to convert dollars to cents

def safe_dollar_to_cent(dollar): components = 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 actually been truncated: -> \".\\ format(parts<1>, decimal_part) standing = 1 ret = int(parts<0>) * 100 multiplier = 10 for i, s in enumerate(decimal_part): ret += int(s) * multiplier multiplier /= 10 return status, ret, msgI am posting right here for seeking various other some pythonic means of law this job.


my intake is intended to be float, the return value should be int.The factor of this implementation is that I found the following incorrect computation.

18.90 * 100 = 1889.9999999999998

python finance
enhance this inquiry
edited Feb 25 \"16 at 17:51
asked Feb 25 \"16 at 11:42

13111 silver- badge33 bronze title
include a comment |

3 answers 3

active earliest Votes
I don\"t prefer the 3 argument return you\"re doing. You\"re utilizing status and also msg to actually carry out the same thing. They both return a signal the success unless the disagreement is truncated. Girlfriend don\"t require both pieces of information. Personally, I\"d simply say that you only should print a note about the dollar being truncated so that the role only returns the cents value.

See more: Kenmore Refrigerator Model 596 Cubic Feet, Kenmore Refrigerator Model 596 Size

Now, you\"re likewise overlooking a very simple formula to transform this:

cents = dollars * 100You don\"t require anything more facility than that for the simple function:

def safe_dollar_to_cent(dollar): cents = disagreement * 100 return centsIf you\"re not sure that dollar will certainly be a number, you can try converting it:

def safe_dollar_to_cent(dollar): cents = float(dollar) * 100 return centsAs because that truncating, i think it\"s much better as an option. Let the user pick whether or not something will certainly be truncated:

def safe_dollar_to_cent(dollar, truncate=True): cents = float(dollar) * 100 if truncate: return int(cents) else: return centsint will turn cents right into a entirety number rather of a decimal, for this reason it\"s properly truncating every little thing after the ..