Reputation: 826
I'm sorry if this is a duplicate but I haven't found anything relevant to it.
So, how can I print 0
for the numbers having a whole square root with the following code?
for (n = 1.0; n <= 10; n++)
{
Console.WriteLine ("Fractional Part : {0 :#.####}", (Math.Sqrt(n) - (int) Math.Sqrt(n)));
}
Upvotes: 5
Views: 359
Reputation: 98810
How about using The numeric "N"
format specifier with 4
precision?
for (var n = 1.0; n <= 10; n++)
{
Console.WriteLine("Fractional Part : {0}",
(Math.Sqrt(n) - (int)Math.Sqrt(n)).ToString("N4"));
}
Result is:
Fractional Part : 0.0000
Fractional Part : 0.4142
Fractional Part : 0.7321
Fractional Part : 0.0000
Fractional Part : 0.2361
Fractional Part : 0.4495
Fractional Part : 0.6458
Fractional Part : 0.8284
Fractional Part : 0.0000
Fractional Part : 0.1623
Upvotes: 4
Reputation: 66469
Assuming a leading zero on the other fractional results is acceptable, and since your result is always in the range of [0,1)
, you could just change #.####
to 0.####
.
for (var n = 1.0; n <= 10; n++)
{
Console.WriteLine("Fractional Part : {0:0.####}", (Math.Sqrt(n) - (int) Math.Sqrt(n)));
}
Results:
Fractional Part : 0
Fractional Part : 0.4142
Fractional Part : 0.7321
Fractional Part : 0
Fractional Part : 0.2361
Upvotes: 7