number_to_words.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 金额英文大写转换
  5. """
  6. from num2words import num2words
  7. import math
  8. def amount_to_english_words(amount: float) -> str:
  9. """
  10. 将金额转换为英文大写
  11. Args:
  12. amount: 金额数字,如 14488
  13. Returns:
  14. 英文大写字符串,如 "FOURTEEN THOUSAND FOUR HUNDRED AND EIGHTY-EIGHT"
  15. """
  16. if amount is None or amount < 0:
  17. return ''
  18. # 四舍五入到整数
  19. amount_int = round(amount)
  20. # 转换为英文单词并大写
  21. words = num2words(amount_int, lang='en')
  22. return words.upper().replace('-', ' ').replace(',', '')
  23. def calculate_payment_split(total_amount: float) -> tuple:
  24. """
  25. 计算30%和70%的付款金额
  26. 规则:30%向上取整,70% = 总金额 - 30%
  27. 确保 30% + 70% = 总金额
  28. Returns:
  29. (deposit_30, balance_70)
  30. """
  31. total_int = round(total_amount)
  32. deposit_30 = math.ceil(total_int * 0.30)
  33. balance_70 = total_int - deposit_30
  34. return deposit_30, balance_70
  35. def format_say_us_only(amount: float) -> str:
  36. """
  37. 格式化为 "SAY US {大写} only"
  38. Args:
  39. amount: 金额数字
  40. Returns:
  41. 如 "SAY US FOURTEEN THOUSAND FOUR HUNDRED AND EIGHTY EIGHT only"
  42. """
  43. words = amount_to_english_words(amount)
  44. return f"SAY US {words} only"
  45. if __name__ == '__main__':
  46. # 测试
  47. print(format_say_us_only(14488))
  48. print(format_say_us_only(4346.4))
  49. print(format_say_us_only(10141.6))