-2

I'm making a simple calculator in c# and and everything works well until I try dividing numbers that should give decimal places. How to display 2 decimal places in these cases?

I've tried putting #.## after .ToString.

{label1.Text = (divide / Convert.ToInt64(label1.Text)).ToString("#.##");}

I expect the output of 5/4 to be 1.25, but it is 1.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Filip
  • 1
  • 1
  • What is the type of `divide`? If it's an integer type then you're doing integer division. – Lance U. Matthews Aug 06 '19 at 17:13
  • 1
    That's because integers don't contain decimals. You would have to do the same but convert into a float or decimal data type – Saamer Aug 06 '19 at 17:15
  • 1
    You need to use float as your type, Convert to float instead and make divide too float – Bosco Aug 06 '19 at 17:16
  • 1
    If you are doing a calculator, you may be happier with the `decimal` type (compared to `float` or `decimal`). It's more exact. The `float` and (especially) `decimal` types have a wider range, but less accuracy. It would likely be worth it for you to spend some time understanding the difference between integral types, traditional floating point types and `decimal` if you are writing a calculator. – Flydog57 Aug 06 '19 at 17:18
  • Also read up on integer division and modulus. If you divide integer 7 by integer 4 (7/4), you will get 1. However, if you evaluate the modulus of those two numbers (7%4), you will find out that the remainder is 3. – Flydog57 Aug 06 '19 at 17:19

1 Answers1

0

convert the number to float instead of int,

{label1.Text = ((float)divide / float.Parse(label1.Text)).ToString("n2");}
ashok19r91d
  • 474
  • 6
  • 17