James123
James123

Reputation: 11652

How to get integer quotient when divide two values in c#?

I want get integer quotient when I divide two values. Per example

X=3
Y=2
Q=X/Y = 1.5 // I want get 1 from results


X=7
Y=2
Q=X/Y=3.5 //I want get only 3 from results

Upvotes: 20

Views: 44743

Answers (6)

Pranav
Pranav

Reputation: 135

There is another elegant way of getting quotient and remainder in .NET using Math.DivRem() method which takes 2 input parameter, 1 output parameter and returns integer.

using System;

For dividend: 7 and divisor: 2

To get only quotient(q)

int q = Math.DivRem(7, 2, _);
//requires C# >= 7.0 to use Discards( _ )

To get quotient(q) and remainder(r)

int q = Math.DivRem(7, 2, out int r);

Math.DivRem() has 2 overloads for 32-bit and 64-bit signed integers.

Upvotes: 1

Gopal Kataria
Gopal Kataria

Reputation: 11

try using simple maths

int X = 10 ;
int Y = 3 ; 
int Q = ( X - ( X % Y ) ) / Y  ; // ( it will give you the correct answer ) 

It works by subtracting the remainder beforehand from the first number so that we don't get a remainder at all !

Upvotes: 1

Greg Bogumil
Greg Bogumil

Reputation: 1923

Try Math.Truncate. This should do it.

Upvotes: 12

Dave
Dave

Reputation: 1234

In VB.NET there is the integer division operator (\). It returns only the integer portion of the division. This comes all the way from the original Dartmouth BASIC so it exists in most forms of BASIC.

Upvotes: 9

Ben Lesh
Ben Lesh

Reputation: 108471

try Math.Floor()

Upvotes: 7

Anthony Pegram
Anthony Pegram

Reputation: 126804

Integer math is going to do this for you.

int x = 3 / 2; // x will be 1
int y = 7 / 2; // y will be 3
int z = 7 % 2; // z will be 1

If you were using decimal or floating-point values in your equations, that would be different. The simplest answer is to cast the result to an int, but there are static Math functions you could also use.

double a = 11d;
double b = 2d;
int c = (int)(a / b); // showing explicit cast, c will be 5

Upvotes: 33

Related Questions