Skip to content

Instantly share code, notes, and snippets.

@zooyf
Created June 28, 2019 05:39
Show Gist options
  • Save zooyf/f0de324dc1797b92235f4081e851520b to your computer and use it in GitHub Desktop.
Save zooyf/f0de324dc1797b92235f4081e851520b to your computer and use it in GitHub Desktop.
python precision calculation
def yuan2fen(amount):
if isinstance(amount, str):
amount = float(amount)
a = amount * 100
z = str(a).split(".")
if len(z) == 2:
if int(z[1][0]) > 4:
return int(a) + (1 if a > 0 else -1)
else:
return int(a)
else:
return int(a)
def yuan2fen2(amount):
if isinstance(amount, str):
amount = float(amount)
a = int(amount * 1000)
l = a % 10
s1 = 1 if l > 4 else 0
s = int(a / 10) + (s1 if a > 0 else -s1)
return s
if __name__ == '__main__':
assert yuan2fen(38.91) == 3891
assert yuan2fen(38.915) == 3892
assert yuan2fen(0.915) == 92
assert yuan2fen(.915) == 92
assert yuan2fen(38.9) == 3890
assert yuan2fen(38.) == 3800
assert yuan2fen(-38.) == -3800
assert yuan2fen(120000000000000) == 12000000000000000
assert yuan2fen(-120000000000000) == -12000000000000000
assert yuan2fen(0) == 0
assert yuan2fen(.0) == 0
assert yuan2fen(.004) == 0
assert yuan2fen(.005) == 1
assert yuan2fen(-.005) == -1
assert yuan2fen(-0.005) == -1
assert yuan2fen(0.005) == 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment