當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


JavaScript Number toFixed()用法及代碼示例

toFixed()方法將數字轉換為字符串。這toFixed()方法將字符串四舍五入到指定的小數位數。

Notes:

  • The toFixed() method rounds the number if necessary.
  • If the specified number of digits is greater than the actual number of digits after the decimal point, zeros are added to the end of the string representation.
  • If the specified number of digits is less than the actual number of digits after the decimal point, the number is rounded.

用法:

number.toFixed( value );

參數:

  • value:它表示小數點後出現的位數。

返回值:

它返回字符串表示形式的數字。該數字的小數點後位數與 toFixed() 方法中提到的完全相同。

示例 1:使用帶有參數 1 的 toFixed() 方法,將小數點顯示為一位。

Javascript


let test=213.73145;
console.log(test.toFixed(1));
輸出
213.7

示例 2:使用不帶任何參數的toFixed()方法,如果toFixed()方法中沒有指定參數,則不顯示小數點後的任何數字。

Javascript


let test=213.73145;
console.log(test.toFixed());
輸出
214

示例 3:使用帶有參數的 toFixed() 方法,如果在 toFixed() 方法中指定了參數,則將返回一個以字符串表示的數字,該數字在小數點後具有完全相同的位數。

Javascript


let test=213.73145;
console.log(test.toFixed(3));
輸出
213.731

示例4:使用toFixed()方法,其中數字為指數形式。 toFixed() 方法可用於將指數數轉換為小數點後具有特定位數的字符串表示形式。

Javascript


let test=2.13e+15;
console.log(test.toFixed(2));
輸出
2130000000000000.00

支持的瀏覽器:

  • 穀歌瀏覽器 1 及以上版本
  • Internet Explorer 5.5 及更高版本
  • Microsoft Edge 12 及更高版本
  • 火狐瀏覽器1及以上版本
  • Apple Safari 2 及更高版本
  • Opera 7 及以上版本

我們有 Javascript 數字對象方法的完整列表,要檢查這些方法,請瀏覽此Javascript Number 完整參考文章。



相關用法


注:本文由純淨天空篩選整理自Shubrodeep Banerjee大神的英文原創作品 JavaScript Number toFixed() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。