Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

197
Vistas
Javascript: prevent parseFloat from converting large number to scientific notation

I have some data in a node app which are numbers in string format. I'm trying to parse them and round off to 3 decimals by parseFloat(num).toFixed(3). Since the numbers are very large, it is automatically converting them to scientific notation (eg 2.0210702881736412e+37). I switched to using parseInt(), Number() but nothing works. How do I get around this?

The data object is very huge so I'm skeptical to use a custom converter function which converts the exponential form to decimal, since it might impact performance.

7 months ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Use BigInt

const num = BigInt(2.0210702881736412e+37);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt

BigInt values are similar to Number values in some ways, but also differ in a few key matters: A BigInt value cannot be used with methods in the built-in Math object and cannot be mixed with a Number value in operations; they must be coerced to the same type. Be careful coercing values back and forth, however, as the precision of a BigInt value may be lost when it is coerced to a Number value.

How you use BigInt for it: BigInt(n).toString();

const num = BigInt(2.0210702881736412e+37);
// 20210702881736411847466551731631947776n

const strNum = num.toString();
// 20210702881736411847466551731631947776

Edit, additional info

Bigint library (or also the builtin data type) can only handle integers. I think try the JavaScript numeric operation library seems to be the fastest way to calculate the decimal point. A bignumber library typically works with arbitrary-precision floating-point numbers. There are several recommended libraries. bignumber.js Or BigNumber

7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.