首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

number.toFixed

toFixed()方法使用定点表示法来格式化一个数。

语法

代码语言:javascript
复制
numObj.toFixed([digits])

参数

digits小数点后数字的个数;介于 0 到 20 (包括)之间,实现环境可能支持更大范围。如果忽略该参数,则默认为 0。

返回值

所给数值的定点数表示法的字符串形式。

异常

RangeError如果digits参数太小或太大。0 到 20(包括)之间的值不会引起?RangeError。实现环境(implementations)也可以支持更大或更小的值。TypeError如果该方法在一个非Number类型的对象上调用。

描述

一个数值的字符串表现形式,不使用指数记数法,而是在小数点后有 digits(注:digits具体值取决于传入参数)位数字。该数值在必要时进行四舍五入,另外在必要时会用 0 来填充小数部分,以便小数部分有指定的位数。 如果数值大于?1e+21,该方法会简单调用?Number.prototype.toString()并返回一个指数记数法格式的字符串。

示例

使用toFixed

代码语言:javascript
复制
var numObj = 12345.6789;

numObj.toFixed();       // Returns '12346': note rounding, no fractional part
numObj.toFixed(1);      // Returns '12345.7': note rounding
numObj.toFixed(6);      // Returns '12345.678900': note added zeros
(1.23e+20).toFixed(2);  // Returns '123000000000000000000.00'
(1.23e-10).toFixed(2);  // Returns '0.00'
2.34.toFixed(1);        // Returns '2.3'
2.35.toFixed(1);        // Returns '2.4'. Note that it rounds up in this case.
-2.34.toFixed(1);       // Returns -2.3 (due to operator precedence, negative number literals don't return a string...)
(-2.34).toFixed(1);     // Returns '-2.3' (...unless you use parentheses)

规范

Specification

Status

Comment

ECMAScript 3rd Edition (ECMA-262)

Standard

Initial definition. Implemented in JavaScript 1.5.

ECMAScript 5.1 (ECMA-262)The definition of 'Number.prototype.toFixed' in that specification.

Standard

?

ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'Number.prototype.toFixed' in that specification.

Standard

?

ECMAScript Latest Draft (ECMA-262)The definition of 'Number.prototype.toFixed' in that specification.

Living Standard

?

浏览器兼容性

Feature

Chrome

Edge

Firefox

Internet Explorer

Opera

Safari

Basic Support

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

Feature

Android

Chrome for Android

Edge mobile

Firefox for Android

IE mobile

Opera Android

iOS Safari

Basic Support

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

(Yes)

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com