試一試
function expo(x, f) {
return Number.parseFloat(x).toExponential(f);
}
console.log(expo(123456, 2));
// Expected output: "1.23e+5"
console.log(expo("123456"));
// Expected output: "1.23456e+5"
console.log(expo("oink"));
// Expected output: "NaN"
語法
js
toExponential()
toExponential(fractionDigits)
引數
fractionDigits可選-
可選。一個整數,指定小數點後的位數。預設為表示該數字所需的位數。
返回值
一個字串,表示給定的 Number 物件以指數記法表示,小數點前有一位數字,小數點後有 fractionDigits 位數字(四捨五入)。
異常
RangeError-
如果
fractionDigits不是0到100(包含)之間的整數,則丟擲錯誤。 TypeError-
如果此方法在非
Number物件上呼叫,則丟擲該錯誤。
描述
如果省略 fractionDigits 引數,則小數點後的位數將預設為唯一表示該值所需的位數。
如果對數字字面量使用 toExponential() 方法,並且該數字字面量沒有指數且沒有小數點,則在方法呼叫前面的點(.)之前留一個或多個空格,以防止該點被解釋為小數點。
如果一個數字的位數多於 fractionDigits 引數所請求的位數,則該數字將被四捨五入到由 fractionDigits 位數表示的最近的數字。有關四捨五入的討論,請參閱 toFixed() 方法的描述,該描述也適用於 toExponential()。
示例
使用 toExponential
js
const numObj = 77.1234;
console.log(numObj.toExponential()); // 7.71234e+1
console.log(numObj.toExponential(4)); // 7.7123e+1
console.log(numObj.toExponential(2)); // 7.71e+1
console.log((77.1234).toExponential()); // 7.71234e+1
console.log((77).toExponential()); // 7.7e+1
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-number.prototype.toexponential |
瀏覽器相容性
載入中…