Miha M
Miha M

Reputation: 291

C# - Closest number to 0

I apologize if it sounds dumb, I am a beginner in programming. Can somebody explain how can I get the closest number to 0 if for example:

A = -13

B = 5

How can I do this so it can display that in this example B is closest to 0?

I tried some thing with "if" but can't seem to get it work.

Thanks

Upvotes: 2

Views: 15202

Answers (1)

Soner Gönül
Soner Gönül

Reputation: 98750

I feel taking a risk to answer that but if you try to say theirs absolute value with term closest, you can use Math.Abs method and compare them like;

if(Math.Abs(A) > Math.Abs(B))
{
   // B is closer than A
}
else if(Math.Abs(B) > Math.Abs(A))
{
   // A is closer than B
}
else
{
   // They are equal close to zero.
}

It is not clear what are A and B types but this method accepts short, int, long, decimal, double, float etc..

Upvotes: 5

Related Questions