Search code examples
c#structconsole.writeline

How to display float values in c#?


I'm working with structs in c#, and when I want to display average grade of a student like "4.53", it prints "453". Here's the code:

using System;
using System.Buffers;

namespace Struct
{
    struct student
    {
        public string name, surname;
        public float average;
    }

    class Program
    {
        static void Main(string[] args)
        {
            student[] arr = new student[3];
            for (int i = 0; i < 2; i++)
            {
                Console.Write("name {0}. - ", i + 1);
                arr[i].name = Console.ReadLine();
                Console.Write("surname {0}. - ", i + 1);
                arr[i].surname = Console.ReadLine();
                Console.Write("average {0}. - ", i + 1);
                arr[i].average = float.Parse(Console.ReadLine());
            }

            for (int i = 0; i < 2; i++)
            {
                Console.WriteLine("{0} {1} - {2}", arr[i].name, arr[i].surname, arr[i].average);
            }
        }
    }
}

I also tried this:

Console.WriteLine(string.Format("{0} {1} - {2:.0#}", arr[i].name, arr[i].surname, arr[i].average));

but it's not working.


Solution

  • arr[i].average = float.Parse(Console.ReadLine());
    

    Those warnings you see aren't just for show, they're trying to explain to you why the code you wrote is objectively bad.

    Specifically, you're reading a floating point value written by a human who doesn't write numbers correctly according to the country he lives in.

    Since you don't provide this information, let's say you wrote 2.15 on the prompt where your country expects floating point numbers to be written as 2,15, and where the . character is the decimal separator instead. In this case, that average field would get the value 215, which is correct according to your localization rules.

    The warning you ignored hints at one possible solution: specifying a culture information type yourself, in case when it doesn't match the system culture information, and one possible culture that's always a decent default is CultureInfo.InvariantCulture, which uses . for the decimal point and , for the decimal separator.