开发者

How to convert a double to a string without using the CRT

开发者 https://www.devze.com 2022-12-22 00:21 出处:网络
My question has no practical application. I\'m just interested. Suppose, I have a double value and I want to obtain its string rep开发者_Python百科resentation similarly to the printf function. How wou

My question has no practical application. I'm just interested. Suppose, I have a double value and I want to obtain its string rep开发者_Python百科resentation similarly to the printf function. How would I do that without the C runtime library? Let's suppose I'm on the x86 architecture.


Given that you state your question has no practical application, I figure you're trying to learn about floating point number representations.

Thus, if you're looking for a solution without using any library support, start with the format specification. From that you can discern the various "special" values (Infinity, NAN, etc) as well as decoding/calculating the actual numeric value. Once you have the significand and exponent, you know where to put the decimal point. You'll have to write your own itoa type routine. For radices which are a power of two, this can be as simple as a lookup table. For decimal, you'll have to do a little extra math.


you can get all values on left side by (double % 10) and then divide by 10 every time. they will be in right to left.

to get values on right of dot you have to multiply by 10 and then (double % 10). they will be in left-to-right.


If you want to do it simply with a "close enough" result, see my article http://www.exploringbinary.com/quick-and-dirty-floating-point-to-decimal-conversion/ . It describes a simple program that uses floating-point to convert from floating-point to decimal, and explains why that approach can never be accurate for all conversions. (The program doesn't do decimal rounding like printf, but that should be easy enough to add.)

0

精彩评论

暂无评论...
验证码 换一张
取 消