Why does toPrecision return a String?

匆匆过客 提交于 2019-12-02 02:00:15

From the docs: "Returns a string representing the Number object to the specified precision."

toPrecision() seems intended for formatting output, in which case a string is the most reasonable outcome. It represents the final output in a form that will not be mangled by further manipulation.

If you are looking to do some truncation of precision for calculation reasons, I tend to multiply by 10^n where n is the digits I want to keep, take an integer from that and then divide again by the same. This isn't perfect though: in some situations you may invite an overflow. Frankly, I prefer to do more complex financial calculations on the server, where I have a currency, binary coded decimal or similar numeric types.

Assume you have a number like '1.6'. If you format it to have 6 zeroes to the right, you would get a '1.600000'. To the computer, it is still the same number as 1.6, but to you and your website, it is not the same if all your numbers are of different lenghts (which could hurt a parser, for instance).

So, as to avoid it, toPrecision returns a string, or else the interpreter would reformat the number to become '1.6' again.

Robert

The purpose of toPrecision is to truncate the significant decimal digits of a Number to a specified amount. But the datatype of the internal representations of Numbers is binary IEEE-754 double. Therefore it's impossible to store the precise return value in a Number most of the times. As a result of this impreciseness, the return value would have an infinite amount of decimal digits which would render toPrecision void.

So the only reasonable solution to this problem is to return decimal digits. And currently the only reasonable JS datatype for decimal digits is a String.


Here's an example to clarify the impreciseness of Numbers if used for decimal digits:

// the following looks like something with 2 decimal digits:
var number = 1.6;

// but in fact it's a number with an infinite amount of decimal digits.
// let's look at the first 30 of them:
alert(number.toPrecision(30));

// 1.60000000000000008881784197001

Because it is a formatting function.

You need a string for trailing zeros. Currency display is a good example.

The problem is the use of toPrecision. Try it without.

var isNotNumber = parseFloat('1.3');
alert(typeof isNotNumber); //=> number
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!