numberFormat.wxs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /**
  2. * 保留2位小数
  3. * @param value
  4. */
  5. var numberFormat = function (value) {
  6. var v = parseFloat(value)
  7. //强转Float,毕竟有可能返回是String类型的数字
  8. return v.toFixed(2)
  9. }
  10. /**
  11. * 保留4位小数
  12. * @param value
  13. */
  14. var numberFormatFour = function (value) {
  15. var v = parseFloat(value)
  16. //强转Float,毕竟有可能返回是String类型的数字
  17. return v.toFixed(4)
  18. }
  19. /**
  20. * 保留decimal位小数
  21. * @param value 值
  22. * @param decimal 位数
  23. */
  24. function toFixed(value, decimal) {
  25. decimal = decimal || 0;
  26. if (!value) return '0.00';
  27. return parseFloat(value).toFixed(decimal);
  28. }
  29. //取整
  30. function toIntFixed(value) {
  31. if (value == undefined) {
  32. value = 0
  33. }
  34. return parseInt(value);
  35. }
  36. //千分符
  37. function toThousandCents(num) {
  38. if (num == undefined) {
  39. return 0;
  40. }
  41. var num = num + '';
  42. var d = '';
  43. if (num.slice(0, 1) == '-') {
  44. d = num.slice(0, 1);
  45. num = num.slice(1);
  46. }
  47. var len = num.length;
  48. var index = num.indexOf('.');
  49. if (index == -1) {
  50. num = num + '.00';
  51. } else if ((index + 2) == len) {
  52. num = num + '0';
  53. }
  54. var index = num.indexOf('.'); // 字符出现的位置
  55. var num2 = num.slice(-3);
  56. num = num.slice(0, index)
  57. var result = '';
  58. while (num.length > 3) {
  59. result = ',' + num.slice(-3) + result;
  60. num = num.slice(0, num.length - 3);
  61. }
  62. if (num) {
  63. result = num + result;
  64. }
  65. return d + (result + num2)
  66. }
  67. function toPercent(point) {
  68. var percent = parseFloat(point * 100).toFixed(2);
  69. return percent;
  70. }
  71. function toThousandCents2(num) {
  72. if (num == undefined) {
  73. num = 0
  74. }
  75. num.toLocaleString()
  76. }
  77. /**
  78. * //暴露接口调用
  79. */
  80. module.exports = {
  81. toIntFixed: toIntFixed,
  82. toFixed: toFixed,
  83. numberFormat: numberFormat,
  84. numberFormatFour: numberFormatFour,
  85. toThousandCents: toThousandCents,
  86. toPercent: toPercent
  87. }