util.ts 727 B

1234567891011121314151617181920212223242526272829303132333435
  1. function trimExtraChar(value: string, char: string, regExp: RegExp) {
  2. const index = value.indexOf(char);
  3. if (index === -1) {
  4. return value;
  5. }
  6. if (char === '-' && index !== 0) {
  7. return value.slice(0, index);
  8. }
  9. return value.slice(0, index + 1) + value.slice(index).replace(regExp, '');
  10. }
  11. export function formatNumber(
  12. value: string,
  13. allowDot = true,
  14. allowMinus = true
  15. ) {
  16. if (allowDot) {
  17. value = trimExtraChar(value, '.', /\./g);
  18. } else {
  19. value = value.replace(/\./g, '');
  20. }
  21. if (allowMinus) {
  22. value = trimExtraChar(value, '-', /-/g);
  23. } else {
  24. value = value.replace(/-/, '');
  25. }
  26. const regExp = allowDot ? /[^-0-9.]/g : /[^-0-9]/g;
  27. return value.replace(regExp, '');
  28. }