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

302
Visualizações
¿Cómo puedo convertir un valor BigInt de JavaScript a notación científica?

Me gustaría representar un valor bigint de JavaScript en una string en notación científica.

Pensé en Number.toExponential() pero solo funciona para numbers .

 const scientificNotation = n => parseInt(n).toExponential(); console.log(scientificNotation(prompt()));

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Intl admite Bigint:

Resulta que BigInt.prototype.toLocaleString() se puede usar con options para notación científica:

 const fmt /*: BigIntToLocaleStringOptions */ = { notation: 'scientific', maximumFractionDigits: 20 // The default is 3, but 20 is the maximum supported by JS according to MDN. }; const b1 = 1234567890123456789n; console.log( b1.toLocaleString( 'en-US', fmt ) ); // "1.234567890123456789E18"

Respuesta original:

(Este código sigue siendo útil para entornos JS sin soporte Intl o si necesita más de 20 dígitos de precisión):

Debido a que los valores de bigint siempre son integrales, y debido a que bigint.toString() devolverá dígitos de base 10 sin más ceremonia (aparte de un encabezado - para valores negativos), entonces un método rápido y sucio es tomar esos dígitos representados e insertar un punto de raíz (también conocido como punto decimal ) después del primer dígito y agregue el exponente al final, y debido a que es una cadena de base 10, el exponente es el mismo que la longitud de la cadena renderizada (genial, ¿eh?)

 function bigIntToExponential( value: bigint ): string { if( typeof value !== 'bigint' ) throw new Error( "Argument must be a bigint, but a " + ( typeof value ) + " was supplied." ); // const isNegative = value < 0; if( isNegative ) value = -value; // Using the absolute value for the digits. const str = value.toString(); const exp = str.length - 1; if( exp == 0 ) return ( isNegative ? "-" : '' ) + str + "e+0"; const mantissaDigits = str.replace( /(0+)$/, '' ); // Remove any mathematically insignificant zeroes. // Use the single first digit for the integral part of the mantissa, and all following digits for the fractional part (if any). let mantissa = mantissaDigits.charAt( 0 ); if( mantissaDigits.length > 1 ) { mantissa += '.' + mantissaDigits.substring( 1 ); } return ( isNegative ? "-" : '' ) + mantissa + "e+" + exp.toString(); } console.log( bigIntToExponential( 1n ) ); // "1e+0" console.log( bigIntToExponential( 10n ) ); // "1e+1" console.log( bigIntToExponential( 100n ) ); // "1e+2" console.log( bigIntToExponential( 1000n ) ); // "1e+3" console.log( bigIntToExponential( 10000n ) ); // "1e+4" console.log( bigIntToExponential( 1003n ) ); // "1.003e+3" console.log( bigIntToExponential( 10000000003000000n) ); // "1.0000000003e+16" console.log( bigIntToExponential( 1234567890123456789n ) ); // "1.234567890123456789e+18" console.log( bigIntToExponential( 12345678901234567898765432109876543210n ) ); // "1.234567890123456789876543210987654321e+37" console.log( bigIntToExponential( -1n ) ); // "-1e+0" console.log( bigIntToExponential( -10n ) ); // "-1e+1" console.log( bigIntToExponential( -100n ) ); // "-1e+2" console.log( bigIntToExponential( -1000n ) ); // "-1e+3"
about 4 years ago · Santiago Trujillo 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