Rohit
Rohit

Reputation: 1550

Casting from "Double to Float" rounding off decimal places

Can anyone please help me understand that why output for float is rounding off decimal ?

Code -

static void Main(string[] args)
{
    float f = (float)Math.Round(Convert.ToDouble("270825.27000000000000"), 2);
    double d = Math.Round(Convert.ToDouble("270825.27000000000000"), 2);

    Console.WriteLine("Float  - " + f.ToString());
    Console.WriteLine("Double - " + d.ToString());

    Console.Read();
}

Output -

enter image description here

Thanks in Advance.

Upvotes: 0

Views: 1637

Answers (1)

profesor79
profesor79

Reputation: 9473

you are casting double to float, so basicly you have:

  1. conversion to double but should be float
  2. rounding which is double
  3. casting

     float f = (float)Math.Round(float.Parse("270825.27000000000000"), 2);
     double d = Math.Round(Convert.ToDouble("270825.27000000000000"), 2);    
     Console.WriteLine("Float  - " + f.ToString());    
     Console.WriteLine("Double - " + d.ToString());
    

results are:

Float - 270825.3

Double - 270825.27

so use decimal

decimal f = (decimal)Math.Round(decimal.Parse("270825.27000000000000"), 2);
Console.WriteLine("Decimal  - " + f.ToString());

270825.27

Upvotes: 1

Related Questions