numbers.hpp 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /*
  2. * numbers.hpp
  3. *
  4. * Created on: 2021年4月7日
  5. * Author: pengzc
  6. */
  7. #ifndef _FY_NUMBERS_HPP_
  8. #define _FY_NUMBERS_HPP_
  9. #include <string.h>
  10. #include <stdint.h>
  11. #include <math.h>
  12. #include <string>
  13. namespace fy {
  14. // https://github.com/zhao520a1a/NumToCN/blob/master/src/NumToCn.java
  15. /**
  16. * 以分为单位,将数字转换为中文大写
  17. */
  18. std::string number_to_currency(int64_t cent) {
  19. const char* CN_NUMBER[] = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };
  20. const char* CN_UNIT[] = { "分", "角", "圆", "拾", "佰", "仟", "万", "拾", "佰", "仟",
  21. "亿", "拾", "佰", "仟", "兆", "拾", "佰", "仟", "顺" };
  22. const char* CN_NEGATIVE = "负";
  23. const char* CN_FULL = "整";
  24. const char* CN_ZERO_FULL = "零圆整";
  25. std::string currency;
  26. //若输入为0,输出零圆整;
  27. if (cent == 0) {
  28. return CN_ZERO_FULL;
  29. }
  30. int64_t number = abs(cent);
  31. int numIndex = 0; //记录数字的个数;
  32. bool getZero = false;
  33. /*
  34. * 思路:要先判断一下小数部分的具体情况;究其根本是因为:小数部分和整数部分在处理“0”的问题上略有不同;避免出现如图1所示的情况;
  35. */
  36. //得到小数部分(小数点后两位);
  37. int64_t scale = number % 100;
  38. if (scale == 0) { //若小数部分为"00"时的情况;骚年,不要忘了在最后追加特殊字符:整
  39. numIndex += 2;
  40. getZero = true;
  41. number /= 100; // 从number去掉为0数;
  42. currency.append(CN_FULL);
  43. } else if (scale % 10 == 0) { //若小数部分为"*0"时的情况;
  44. numIndex += 1;
  45. getZero = true;
  46. number /= 10; // 从number去掉为0数;
  47. }
  48. //排除上述两种小数部分的特殊情况,则对小数和整数的处理就是一样一样一样地了!
  49. while (true) {
  50. //循环结束条件;
  51. if (number <= 0) {
  52. break;
  53. }
  54. //每次通过取余来得到最后一位数;
  55. int numUnit = (int) (number % 10);
  56. if (numUnit != 0) {
  57. currency.insert(0, CN_UNIT[numIndex]); //先添加单位
  58. currency.insert(0, CN_NUMBER[numUnit]); //在添加根据数字值来对应数组中的中文表述;
  59. getZero = false; //表明当前数不是0;
  60. } else {
  61. //意思是它的上一次的数不是零,那么打印出零;
  62. if (!getZero) {
  63. currency.insert(0, CN_NUMBER[numUnit]);
  64. }
  65. //若角分位为零,那么打印零;
  66. if (numIndex == 2) {
  67. if (number > 0) {
  68. currency.insert(0, CN_UNIT[numIndex]);
  69. }
  70. } else if ((numIndex - 2) % 4 == 0 && number % 1000 != 0) {
  71. //第一个条件是为了每隔4位,打印“圆,万,亿”;第二个条件是为了避免出现如图3的情况;
  72. currency.insert(0, CN_UNIT[numIndex]);
  73. }
  74. getZero = true; //将其置为true,那么如果下一位还是0,也不会再打印一遍'零';避免出现图2的情况;
  75. }
  76. // 从number每次都去掉最后一个数
  77. number = number / 10;
  78. numIndex++;
  79. }
  80. // 为负数,就在最前面追加特殊字符:负
  81. if (cent < 0) {
  82. currency.insert(0, CN_NEGATIVE);
  83. }
  84. return currency;
  85. }
  86. } /* namespace fy */
  87. #endif /* JNI_NUMBERS_HPP_ */