Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Division returns zero

Tags:

c#

This simple calculation is returning zero, I can't figure it out:

decimal share = (18 / 58) * 100; 
like image 443
Zo Has Avatar asked Feb 15 '12 06:02

Zo Has


People also ask

Can a division result in zero?

Dividing any number by itself will always result in the number one. Any number multiplied by zero equals zero. The rule we're learning about today might sound like the opposite of that last one: You can't divide any number by zero.

Why do I get 0 when I divide in Python?

In Python 2, 25/100 is zero when performing an integer divison. since the result is less than 1 . You can "fix" this by adding from __future__ import division to your script. This will always perform a float division when using the / operator and use // for integer division.

How does division work in C?

In the C Programming Language, the div function divides numerator by denominator. Based on that division calculation, the div function returns a structure containing two members - quotient and remainder.

How do you divide in C#?

The symbol used to represent division is the forward slash (/). If you want to divide one number by another, you'll need to place the forward slash character between them. Using the same values for a and b as in the example above, check out how to divide two numbers in C# below: Console.


2 Answers

You are working with integers here. Try using decimals for all the numbers in your calculation.

decimal share = (18m / 58m) * 100m; 
like image 180
Daniel Lee Avatar answered Sep 24 '22 17:09

Daniel Lee


18 / 58 is an integer division, which results in 0.

If you want decimal division, you need to use decimal literals:

decimal share = (18m / 58m) * 100m; 
like image 34
Petar Ivanov Avatar answered Sep 25 '22 17:09

Petar Ivanov