简体   繁体   中英

Format input to currency format using regex

I want to format an input to a valid currency string, it should format like this:

input 443gr%%g4 output 4434

input gg443.4 output 443.40

input 443,4 output 443.40

Only numbers and . are a valid output. And when there is . it should have fixed 2 numbers after.

This is my code but it doesn't work correctly:

    format(input: any): any {
    if (input === null || input === undefined || input === "") return null;

    const newInput = input
      .toString()
      .replace(/[^\d\.,]/g, "")
      .replace(",", ".")
      .replace(/\./, "x")
      .replace(/\./g, "")
      .replace(/x/, ".")
      .match(/^\d+([\.,]\d{0,2})?/g);

    if (newInput) return newInput[0].replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1 ").trim();

    return '';
  }

You can use

 const numbers = ['443gr%%g4', 'gg443.4', '443,4', '4.4,3,12344']; numbers.forEach(x=> console.log( x.replace(/[^\d.,]+/g,'').replace(/[.,](?,[^.,]*$)/g. ''),replace(','.'.').replace(/(\,\d{2})\d*$/. '$1')?replace(/(\d)(?=(\d{3})+(,;\d))/g, '$1 ') ) );

Here,

  • .replace(/[^\d.,]+/g,'') - removes all chars but digits, dots and commas
  • .replace(/[.,](?,[^.,]*$)/g, '') - gets rid of all commas and periods that are not final in the string (only last . or , is kept)
  • .replace(',','.') - replaces the only , with . (if present)
  • .replace(/(\.\d{2})\d*$/, '$1') - removes any fractional digits after first two
  • .replace(/(\d)(?=(\d{3})+(?,\d))/g, '$1 ') - adds spaces as thousand separators.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM