numberFormat.wxs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. console.log(value)
  32. if (value == undefined) {
  33. value = 0
  34. }
  35. return parseInt(value);
  36. }
  37. //千分符
  38. function toThousandCents(num) {
  39. if(num == undefined){
  40. return 0;
  41. }
  42. var num = num + '';
  43. var d = '';
  44. if (num.slice(0, 1) == '-'){
  45. d = num.slice(0, 1);
  46. num = num.slice(1);
  47. }
  48. var len = num.length;
  49. var index = num.indexOf('.');
  50. if (index == -1) {
  51. num = num + '.00';
  52. } else if ((index + 2) == len) {
  53. num = num + '0';
  54. }
  55. var index = num.indexOf('.'); // 字符出现的位置
  56. var num2 = num.slice(-3);
  57. num = num.slice(0,index)
  58. var result = '';
  59. while (num.length > 3) {
  60. result = ',' + num.slice(-3) + result;
  61. num = num.slice(0, num.length - 3);
  62. }
  63. if (num) {
  64. result = num + result;
  65. }
  66. return d + (result + num2)
  67. }
  68. function toPercent(point){
  69. var percent = parseFloat(point*100).toFixed(2);
  70. return percent;
  71. }
  72. function toThousandCents2(num) {
  73. if(num == undefined){
  74. num = 0
  75. }
  76. num.toLocaleString()
  77. }
  78. /**
  79. * //暴露接口调用
  80. */
  81. module.exports = {
  82. toIntFixed: toIntFixed,
  83. toFixed: toFixed,
  84. numberFormat: numberFormat,
  85. numberFormatFour: numberFormatFour,
  86. toThousandCents: toThousandCents,
  87. toPercent: toPercent
  88. }