简体   繁体   中英

Number.prototype.toString (for floats) implementation

I recently found out that you can call toString() on floating point numbers in JS with a radix, but I'm confused on its implementation. For example, 3.1459.toString(16) in JS, returns 3.2559b3d07c84c . From my testing it seems that the numeric part is a straightforward conversion to the equivalent radix, but this doesn't hold true for the fractional part? How exactly are the characters determined?

I've found what I believe is the source for that in V8. It is similar to what was posted in the comments about converting the fraction to hexadecimal, but there is additional rounding and precision differences.

If you are looking for converting a decimal fraction to a different radix system, you could multiply the fractional part with the radix, get the integer value in the radix like notation and perform the same until you get zero or get a limit of digits.

 let frac10 = 0.1459, frac16 = '', limit = 15; while (frac10 && --limit) { const integer = Math.floor(frac10 *= 16); frac16 += integer.toString(16); frac10 -= integer; } console.log(frac16);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM