[英]How can I convert a JavaScript BigInt value to Scientific Notation?
我想以科學計數法將 JavaScript bigint
值呈現為string
。
我想到了Number.toExponential()
但顯然它不適用於bigint
:
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
或需要超過 20 位精度的 JS 環境仍然有用):
因為bigint
值始終是整數,並且因為bigint.toString()
將返回 base-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 str + "e+0";
const mantissaDigits = str.replace( /(0+)$/, '' ); // Remove any mathematically insignificant zeroes.
let manitssa = mantissaDigits.charAt( 0 ) + "." + mantissaDigits.substring( 1 ); // Use the single first digit for the integral part of the mantissa, and all following digits for the fractional part.
return ( isNegative ? "-" : '' ) + manitssa + "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( 10000000003000000n) ); // "1.0000000003e+16"
console.log( bigIntToExponential( 1234567890123456789n ) ); // "1.234567890123456789e+18"
console.log( bigIntToExponential( -1n ) ); // "-1e+0"
console.log( bigIntToExponential( -10n ) ); // "-1e+1"
console.log( bigIntToExponential( -100n ) ); // "-1e+2"
console.log( bigIntToExponential( -1000n ) ); // "-1e+3"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.