-1

I'm looking to parse and format a percent directly in an input on user keystrokes so I don't have to worry about any mapping on submit/load with respect to api data. I want to show the value in a user-friendly way ([100%] instead of [1], [12 %] instead of [.12].

iamaword
  • 1,327
  • 8
  • 17

1 Answers1

0

I ended up able to do it this way (using big.js as a helper library to deal with rounding issues). The stumbling block was allowing the entry of normal decimal places even though the number will often implicitly has a decimal place because of the way it's parsed.

export const percentParser = (val: string) => {
  const value = val?.replace(/[^0-9.]/g,'');
  const multipleDecimalPlaces = value.match(/.*\..*\./g)
  if(value && !Number.isNaN(parseFloat(value))) {
    if(!multipleDecimalPlaces && value[value.length-1] === '.') {
      return +(new Big(parseFloat(value)).div(100)) + '.';
    } else {
      return +(new Big(parseFloat(value)).div(100));
    }
  } else {
    return;
  }
}

export const percentFormatter = (value: string) => {
  if(value[value.length -1] === '.') {
    return value ? (+new Big(parseFloat(value)).times(100)) + '.': undefined;
  } else {
    return value ? (+new Big(parseFloat(value)).times(100)): undefined;
  }
}
iamaword
  • 1,327
  • 8
  • 17