Skip to content Skip to sidebar Skip to footer

Why Does Toprecision Return A String?

View this code: function testprecision(){ var isNotNumber = parseFloat('1.3').toPrecision(6); alert(typeof isNotNumber); //=> string } I would have expected a number. I

Solution 1:

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.

Solution 2:

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.

Solution 3:

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:varnumber = 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

Solution 4:

Because it is a formatting function.

Solution 5:

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

Post a Comment for "Why Does Toprecision Return A String?"