Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

308
Views
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>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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 })
};
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!