当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。