Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing whole numbers with {#} in C#?

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)));
}

Current O/P: enter image description here

like image 952
Zaid Khan Avatar asked Apr 24 '16 11:04

Zaid Khan


People also ask

What is the rule of whole numbers?

In chemistry, the whole number rule states that the masses of the isotopes are whole number multiples of the mass of the hydrogen atom. The rule is a modified version of Prout's hypothesis proposed in 1815, to the effect that atomic weights are multiples of the weight of the hydrogen atom.

How do you print 1 100 on the range in Python?

Python Create List from 0 to 100. A special situation arises if you want to create a list from 0 to 100 (included). In this case, you simply use the list(range(0, 101)) function call.


2 Answers

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
like image 55
Grant Winney Avatar answered Sep 21 '22 02:09

Grant Winney


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
like image 29
Soner Gönül Avatar answered Sep 19 '22 02:09

Soner Gönül