Turn float into string

我的未来我决定 提交于 2019-11-27 16:23:50

Formatting a floating point number is rather non-trivial. Search e.g. for the Dragon4 algorithm (here is one result).

Very, very naively, you could try this:

  1. Handle NaN and Infinity.

  2. Print the sign (check < 0). Assume henceforth the number is positive real.

  3. If >= 1, truncate and use familiar integer formatting to print the integral part. (There should be a machine instruction for that on any hardware that has a floating point unit.)

  4. Print the decimal separator; now keep multiplying by 10 and print the truncated integral digit.

  5. Stop when you've reached the desired precision; think about rounding the last digit correctly.

If it is acceptable to print as 1.d1d2d3d4d5…*2^e1e2e3, then converting a floating-point number to decimal(-ish) representation can be simple. An implementation can be found here.

If you need a scientific 1.d1d2…*10^e1e2e3 representation, then the naïve approach to repeatedly divide by 10 and extract digits from the number that you have in floating-point format. You will need some sort of multi-precision integer library. (Repeatedly multiply by 10 to extract the digits after the point.)

Kerrek SB's solution is correct. But you can do it faster without any loop (or less number of loops). Just multiply the fraction part with 10precision. Reducing the number or multiplications also reduces the cumulative error if you do the maths in a floating-point type. For precise conversion you have to use a higher precision floating-point type.

For example you want to convert 0.1234567 with 5 digits of precision, multiply the number with 10000 and get the int part. If rounding is needed, multiply it by 100000 and round the last number

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