kkcoderz
kkcoderz

Reputation:

What is the fastest way to round the digit after a decimal (double)?

Ex, I have number 345.38, 2323.805555, 21.3333. I want to get the number after the decimal and round it up.

345.38 --> 4

2323.805555 --> 8

21.3333 --> 3

Upvotes: 1

Views: 2285

Answers (6)

Kunla
Kunla

Reputation:

If you just want the digit immediately following the decimal...couldn't you do something like this?

float value;
int digit = (int)(((value % 1) * 10) + 0.5)

Upvotes: 1

jason
jason

Reputation: 241701

This avoids potential overflow issues:

decimal value;
string[] sep = new[] { NumberFormatInfo.CurrentInfo.NumberDecimalSeparator };
String.Format("{0:0.0}", Math.Round(value, 1)).Split(sep, StringSplitOptions.None)[1][0];

This avoids string conversions and overflow issues:

decimal value;
decimal absValue = Math.Abs(value);
decimal fraction = absValue - Math.Floor(absValue);
int lastDigit = Convert.ToInt32(10 * Math.Round(fraction, 1));

Upvotes: 4

Thorarin
Thorarin

Reputation: 48486

This whole overflow discussion is a little academic, and most likely not the intention of your homework. But should you want to solve that problem:

decimal value = -0.25m;
decimal fractionalPart = Math.Abs(value - Math.Truncate(value));
int digit = (int)Math.Round(10 * fractionalPart, MidpointRounding.AwayFromZero);

Edit: after reading your question again, I noticed that numbers shouldn't always be rounded up like my original answer. However, most people using Math.Round here use the default banker's rounding (to an even number). It depends if you intended -0.25 to result in 2 or 3. The way I'm reading your description, it should be 3 like in this example.

Upvotes: 0

Guffa
Guffa

Reputation: 700562

Get the fractional part, multiply by ten, and round:

double n = 345.38;
int digit = (int)Math.Round((n - Math.Floor(n)) * 10);

This avoids any overflow issues, as the result is already down to one digit when cast to an int.

I have verified that this gives the desired result for your examples.

Upvotes: 0

mmr
mmr

Reputation: 14919

multiply by 10

ceiling (always rounds up, use 'round' to round down if lower than 0.5)

find the result of modding by 10

Like:

float myFloat = 123.38f;
float myBiggerFloat = Math.Ceiling(myFloat * 10.0f);
int theAnswer = ((int)myBiggerFloat % 10);

Or just ask for help for your homework on SO, either way seems to work.

Upvotes: 7

Suroot
Suroot

Reputation: 4423

float myNum = 10.11;
char c = myNum[myNum.ToString().IndexOf(".") + 1];

Upvotes: -2

Related Questions