-5

I'm currently trying to do:

double keyTimes = 789789347928325 * Math.Pi
Console.WriteLine(keyTimes);

And it gives me: 2.4811964133351E+15

I need it to give me the full number of digits for a project, how can I achieve this? I want something like: 2.4811964133351468979725207509245720957294570275973459709345787430 etc.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Yen
  • 19
  • 4
  • 6
    Hint: how many significant digits do you believe `double` is capable of holding, and what's your evidence for it? How many digits are you actually expecting to see? (How many digits do you believe would be in a "perfectly accurate" result from multiplying pi by 789789347928325?) – Jon Skeet Dec 09 '22 at 16:19
  • 1
    Pi can't be represented exactly in any number of decimal digits, bits, or any other base. – President James K. Polk Dec 09 '22 at 16:23
  • 1
    https://stackoverflow.com/questions/5473136/can-c-sharp-store-more-precise-data-than-doubles – Roman Ryzhiy Dec 09 '22 at 16:24
  • 1
    Also the `Math.PI` is a constant with 16 digits after a decimal – radoslawik Dec 09 '22 at 16:28
  • 2
    Does this answer your question? [How to calculate pi to N number of places in C# using loops](https://stackoverflow.com/questions/11677369/how-to-calculate-pi-to-n-number-of-places-in-c-sharp-using-loops) – Heretic Monkey Dec 09 '22 at 16:59

2 Answers2

0

double can hold up to 17 digits, so you should use the decimal which is the floating-point numeric type with the highest precision (28-29 digits). Since the Math.PI constant is a double too you would need to define your own:

var pi = 3.14159265358979323846264338327m;
var keyTimes = 789789347928325 * pi;
// output 2481196413335099.0078141712097

To get better results you could try to find an external library. For example there is a BigDecimal nuget, but it hasn't been updated for long.

radoslawik
  • 915
  • 1
  • 6
  • 14
0

Obtain as many digits of PI as you want, e.g.

https://github.com/eneko/Pi/blob/master/one-million.txt (one million)

https://stuff.mit.edu/afs/sipb/contrib/pi/ (one billion)

Turn PI into BigInteger, do arithmetics, restore the decimal point:

using System.Numerics;

...

string piStr = "3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679";

BigInteger pi = BigInteger.Parse(piStr.Replace(".", ""));

BigInteger value = pi * 789789347928325;

string result = value.ToString().Insert(16, ".");

Console.WriteLine(result);

Output:

2481196413335099.0078141712096700227201776435541531843170785955041765369811708253654976044892515801198900164883582675

Fiddle

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215