作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想将 JavaScript bigint
值呈现为科学计数法中的 string
。
我想到了Number.toExponential()
但它只适用于 numbers
。
const scientificNotation = n => parseInt(n).toExponential();
console.log(scientificNotation(prompt()));
最佳答案
原来 BigInt.prototype.toLocaleString()
可以与 options
一起用于科学记数法:
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"
(此代码对于不支持 Intl
的 JS 环境或者如果您需要超过 20 位的精度仍然有用):
因为 bigint
值始终是整数,并且因为 bigint.toString()
将返回以 10 为底的数字而无需进一步的仪式(除了领先的 -
对于负值)然后一个快速而肮脏的方法是获取那些呈现的数字并在第一个数字之后插入一个小数点(又名小数点)并在指数处添加结束,并且因为它是一个以 10 为底的字符串,所以指数与呈现的字符串的长度相同(整洁,是吧?)
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"
关于javascript - 如何将 JavaScript BigInt 值转换为科学记数法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70470923/
就目前而言,这个问题不适合我们的问答形式。我们希望答案得到事实、引用或专业知识的支持,但这个问题可能会引起辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the he
我是一名优秀的程序员,十分优秀!