Skip to content
Advertisement

Change number format and get it as a number

I am using MUI and Formik to create form. I need to change numbers format in the all inputs:

1000.00 -> 1.000,00

A created function formatNumber(num) to do this, it works. But problem is that it returns string, and my API wait number (I can do nothing with that). I tried to use react-number-format but it also returns string.

So I also made function parseNumber(str) to parse the formatted number from string to number back. Now I need to use this function before the form submit, and I don’t know how to do this properly. The aim is that the user should always see formatted data in the inputs. But after the form submit this data should be sent to the server as a number.

Here is my code:

//"12345678.09" to "12.345.678,09"
export const formatNumber = (num: number | null): string => {  
 const formatNum = num
    ? new Intl.NumberFormat()
        .format(num)
        .replaceAll(",", "_")
        .replaceAll(".", ",")
        .replaceAll("_", ".")
    : "";
  return formatNum;
};

// "12.345.678,09" back to "12345678.09"
export const parseNumber = (str: string | null): number | null => {
  if (str !== null) {
    str = str.trim();
    let result = str.replace(/[^0-9]/g, "");
    if (/[,.]d{2}$/.test(str)) {
      result = result.replace(/(d{2})$/, ".$1");
    }
    return parseFloat(result);
  } else {
    return null;
  }
};

<Formik
  initialValues={initialValues}
  onSubmit={onSubmit}
>
  <Form noValidate onSubmit={handleSubmit}>
    <TextField
      name=“some_value”
      type="string"
      value={formatNumber(values.some_value)}// here I format data that I get from server, the user should change it in the field and send back to server
    />
  </Form>
<Formik>

Advertisement

Answer

You can transform values in handleSubmit function before passing it to api.

const handleSubmit = (values) => {
    values.some_value = parseNumber(values.some_value);
    fetch(apiUrl, { body: values })
};
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement