Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

301
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda