test.html 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. <script>
  11. const formatBigNumber = (number, decimalPlaces = 2) => {
  12. debugger
  13. if (typeof number !== 'number' && typeof number !== 'string') {
  14. return console.warn(`Input must be a number or a string representation of a number. but get ${typeof number}`)
  15. }
  16. number = parseFloat(number)
  17. if (Math.abs(number) < 10000) {
  18. return { count: number.toFixed(decimalPlaces), unit: '' }
  19. }
  20. const units = ['', '万', '亿']
  21. const unitIndex = Math.floor((parseInt(number).toString().length - 1) / 4)
  22. const unit = units[Math.min(unitIndex, 2)]
  23. let result
  24. if (unitIndex > 0) {
  25. result = (number / Math.pow(10, unitIndex * 4)).toFixed(decimalPlaces)
  26. } else {
  27. result = number.toFixed(decimalPlaces)
  28. }
  29. return {
  30. count: result,
  31. unit
  32. }
  33. }
  34. formatBigNumber(3323805.27)
  35. </script>
  36. </body>
  37. </html>