In C#, to convert int to float, we just need to do something like float floatNumber = intNumber
or Convert.ToSingle(intNumber)
. However, when it comes to large number such as 999999999, the system cannot correctly convert the number but convert it into the unwanted number 1E+09. Now the question is, is it possible to convert that large integer into the wanted float number?

- 103
- 4
- 15
-
Look up "What Every Computer Scientist Should Know About Floating-Point Arithmetic". It's something everyone should read, or at least read enough to know why this happens and to know why testing for floating point equality is a **_really_** bad idea. – Flydog57 Dec 17 '18 at 04:04
-
Why float rather than double? – Patricia Shanahan Dec 17 '18 at 04:28
2 Answers
A 32-bit float can't exactly represent an integer that large: It only has 24 bits with which to do it (one is implicit in the format). In 24 bits you can represent 16777215. 16777216 also fits because it is a power of two. 999999999 can't be represented exactly as a number with at most 24 bits multiplied by a power of 2.
See this answer on SO: https://stackoverflow.com/a/3793950/751579
For more information look up details on IEEE floating point 32-bit and 64-bit formats.

- 5,775
- 3
- 34
- 50
-
This a good explanation, but the practical solution would be to use `decimal'. – tymtam Dec 17 '18 at 22:58
-
@tymtam - Perhaps. Depends on the OP's use case, which he did not describe. (E.g., maybe double is appropriate.) – davidbak Dec 18 '18 at 00:18
Can you use decimal type?
Console.WriteLine(999999999.0f.ToString("N"));
Console.WriteLine(999999999.0m.ToString("N"));;
prints
1,000,000,000.00
999,999,999.00
The reference even has a example for a very large number
In this example, the output is formatted by using the currency format string. Notice that
x
is rounded because the decimal places exceed $0.99. The variabley
, which represents the maximum exact digits, is displayed exactly in the correct format.public class TestDecimalFormat { static void Main() { decimal x = 0.999m; decimal y = 9999999999999999999999999999m; Console.WriteLine("My amount = {0:C}", x); Console.WriteLine("Your amount = {0:C}", y); } } /* Output: My amount = $1.00 Your amount = $9,999,999,999,999,999,999,999,999,999.00 */

- 31,798
- 8
- 86
- 126