I'm trying to round up numbers using C# in a way that it always rounds to the next number. For instance:
0.409 -> 0.41
0.401 -> 0.41
0.414 -> 0.42
0.499 -> 0.50
0.433 -> 0.44
Is there a way to do this using .NET built-in functions?
Math.Ceiling can be used.
Math.Ceiling rounds to the nearest integer though, so I advise you do some division/multiplication also:
var notRounded = 0.409;
var rounded = Math.Ceiling(notRounded * 100) / 100;
Explanation: notRounded * 100 gives you 40.9. Math.Ceiling will return 41, so divide this again to 'restore it' back to the original decimal form: 0.41.
One way would be Math.Ceiling as already described.
Another option is to calculate the remainder, and add the difference to round up:
decimal r = 0.409M;
decimal d = r % .01M > 0 ? (r + .01M - r % .01M) : r;
Related
Suppose n is a BigInteger and I want its first 5 digits. I'm thinking in 2 ways:
Dividing n by 10 log10(n)-5 times (so only the first 5 digits would remain).
Get the Substring(0, 5) of n's string.
I have no idea which one is faster or if there is another option that may be better than these.
I would like to hear considerations about it before I test these options (what do you think of them, if there is something better, etc.).
If we want to find out first 5 leading digits, we can exploit integer division:
123 / 1 == 123
12345 / 1 == 12345
1234567 / 100 == 12345
Naive approach is to divide original value by 10 while it is bigger or equal 1_000_000:
1234567 => 123456 => 12345
However, division is expensive especially if we have a huge number (if we have a number with ~1000000 digits we have to divide this number ~1000000 times). To create a faster solution
we can compute an appropriate power of 10 (power computation is fast) and then divide just once:
1234567 / Pow(10, Log10(1234567) - 5 + 1)
So the raw idea is
result = source / BigInteger.Pow(10, (int)BigInteger.Log10(source) - 4);
There are two difficulties here:
Negative numbers (we should take absolute value of source at least when we computing logarithms)
Rounding errors for huge source (what if we have rounding up and have just 4 digits?)
To cope with both problems I compute Log10 myself as Log10(2) * Log2(source):
value.GetBitLength() * 0.30102999566398
this guarantees that I have at least 5 digits but may be 6 in case of rounding errors (note 0.30102999566398 < Log10(2)).
Combining all together:
private static int FirstDigits(BigInteger value) {
if (value.IsZero)
return 0;
int digits = 5;
int result = (int)(value /
BigInteger.Pow(10, (int)(value.GetBitLength() * 0.30102999566398 - digits + 1)));
while (result >= 1_000_000 || result <= -1_000_000)
result /= 10;
return result;
}
This simple calculation is returning zero, I can't figure it out:
decimal share = (18 / 58) * 100;
You are working with integers here. Try using decimals for all the numbers in your calculation.
decimal share = (18m / 58m) * 100m;
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;
Since some people are linking to this from pretty much any thread where the calculation result is a 0, I am adding this as a solution as not all the other answers apply to case scenarios.
The concept of needing to do calculations on various types in order to obtain that type as a result applies, however above only shows 'decimal' and uses it's short form such as 18m as one of the variables to be calculated.
// declare and define initial variables.
int x = 0;
int y = 100;
// set the value of 'x'
x = 44;
// Results in 0 as the whole number 44 over the whole number 100 is a
// fraction less than 1, and thus is 0.
Console.WriteLine( (x / y).ToString() );
// Results in 0 as the whole number 44 over the whole number 100 is a
// fraction less than 1, and thus is 0. The conversion to double happens
// after the calculation has been completed, so technically this results
// in 0.0
Console.WriteLine( ((double)(x / y)).ToString() );
// Results in 0.44 as the variables are cast prior to calculating
// into double which allows for fractions less than 1.
Console.WriteLine( ((double)x / (double)y).ToString() );
Because the numbers are integers and you perform integer division.
18 / 58 is 0 in integer division.
Whenever I encounter such situations, I just upcast the numerator.
double x = 12.0 / 23409;
decimal y = 12m / 24309;
Console.WriteLine($"x = {x} y = {y}");
double res= (firstIntVar * 100f / secondIntVar) / 100f;
when dividing numbers I use double or decimal , else I am getting 0 , with this code even if firstIntVar && secondIntVar are int it will return the expected answer
decimal share = (18 * 100)/58;
Solved: working perfectly with me
int a = 375;
int b = 699;
decimal ab = (decimal)a / b * 100;
What is the best approach to convert floats like so:
0.433432 -> 0.43
0.672919 -> 0.67
3.826342 -> 0.82
6.783643 -> 0.78
i have a float array and want to convert all the values it contains
Thanks :)
You want to get fractional part and truncate it up to two digits. If values are positive and small you can implement it like this:
private static double Solution(double value) {
return (long)((value - (long)value) * 100) / 100.0;
}
Test:
double[] test = new double[] {
0.433432,
0.672919,
3.826342,
6.783643, };
var result = test
.Select(item => $"{item} -> {Solution(item)}")
.ToArray();
Console.Write(string.Join(Environment.NewLine, result));
Outcome:
0.433432 -> 0.43
0.672919 -> 0.67
3.826342 -> 0.82
6.783643 -> 0.78
Edit: What's going on in the Solution method:
value - (long) value - integer part removing
(long) ((...) * 100) - scaling up and truncate
() / 100.0 - scaling down back
If we have, say, 1234.5789 these three stages will be:
0.5789 - integer part removing
57 - scale up and truncate
0.57 - scaling down back
You could subtract the integer value.
for(int i = 0; i < array.Length; i++)
array[i] -= ((int)array[i]);
value = Math.Truncate(100 * value) / 100;
OR
decimal result = TruncateDecimal(0.433432, 2);
This simple calculation is returning zero, I can't figure it out:
decimal share = (18 / 58) * 100;
You are working with integers here. Try using decimals for all the numbers in your calculation.
decimal share = (18m / 58m) * 100m;
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;
Since some people are linking to this from pretty much any thread where the calculation result is a 0, I am adding this as a solution as not all the other answers apply to case scenarios.
The concept of needing to do calculations on various types in order to obtain that type as a result applies, however above only shows 'decimal' and uses it's short form such as 18m as one of the variables to be calculated.
// declare and define initial variables.
int x = 0;
int y = 100;
// set the value of 'x'
x = 44;
// Results in 0 as the whole number 44 over the whole number 100 is a
// fraction less than 1, and thus is 0.
Console.WriteLine( (x / y).ToString() );
// Results in 0 as the whole number 44 over the whole number 100 is a
// fraction less than 1, and thus is 0. The conversion to double happens
// after the calculation has been completed, so technically this results
// in 0.0
Console.WriteLine( ((double)(x / y)).ToString() );
// Results in 0.44 as the variables are cast prior to calculating
// into double which allows for fractions less than 1.
Console.WriteLine( ((double)x / (double)y).ToString() );
Because the numbers are integers and you perform integer division.
18 / 58 is 0 in integer division.
Whenever I encounter such situations, I just upcast the numerator.
double x = 12.0 / 23409;
decimal y = 12m / 24309;
Console.WriteLine($"x = {x} y = {y}");
double res= (firstIntVar * 100f / secondIntVar) / 100f;
when dividing numbers I use double or decimal , else I am getting 0 , with this code even if firstIntVar && secondIntVar are int it will return the expected answer
decimal share = (18 * 100)/58;
Solved: working perfectly with me
int a = 375;
int b = 699;
decimal ab = (decimal)a / b * 100;
How can I round values to nearest integer?
For example:
1.1 => 1
1.5 => 2
1.9 => 2
"Math.Ceiling()" is not helping me. Any ideas?
See the official documentation for more. For example:
Basically you give the Math.Round method three parameters.
The value you want to round.
The number of decimals you want to keep after the value.
An optional parameter you can invoke to use AwayFromZero rounding. (ignored unless rounding is ambiguous, e.g. 1.5)
Sample code:
var roundedA = Math.Round(1.1, 0); // Output: 1
var roundedB = Math.Round(1.5, 0, MidpointRounding.AwayFromZero); // Output: 2
var roundedC = Math.Round(1.9, 0); // Output: 2
var roundedD = Math.Round(2.5, 0); // Output: 2
var roundedE = Math.Round(2.5, 0, MidpointRounding.AwayFromZero); // Output: 3
var roundedF = Math.Round(3.49, 0, MidpointRounding.AwayFromZero); // Output: 3
Live Demo
You need MidpointRounding.AwayFromZero if you want a .5 value to be rounded up. Unfortunately this isn't the default behavior for Math.Round(). If using MidpointRounding.ToEven (the default) the value is rounded to the nearest even number (1.5 is rounded to 2, but 2.5 is also rounded to 2).
Math.Ceiling
always rounds up (towards the ceiling)
Math.Floor
always rounds down (towards to floor)
what you are after is simply
Math.Round
which rounds as per this post
You need Math.Round, not Math.Ceiling. Ceiling always "rounds" up, while Round rounds up or down depending on the value after the decimal point.
there's this manual, and kinda cute way too:
double d1 = 1.1;
double d2 = 1.5;
double d3 = 1.9;
int i1 = (int)(d1 + 0.5);
int i2 = (int)(d2 + 0.5);
int i3 = (int)(d3 + 0.5);
simply add 0.5 to any number, and cast it to int (or floor it) and it will be mathematically correctly rounded :D
You can use Math.Round as others have suggested (recommended), or you could add 0.5 and cast to an int (which will drop the decimal part).
double value = 1.1;
int roundedValue = (int)(value + 0.5); // equals 1
double value2 = 1.5;
int roundedValue2 = (int)(value2 + 0.5); // equals 2
Just a reminder. Beware for double.
Math.Round(0.3 / 0.2 ) result in 1, because in double 0.3 / 0.2 = 1.49999999
Math.Round( 1.5 ) = 2
You have the Math.Round function that does exactly what you want.
Math.Round(1.1) results with 1
Math.Round(1.8) will result with 2.... and so one.
this will round up to the nearest 5 or not change if it already is divisible by 5
public static double R(double x)
{
// markup to nearest 5
return (((int)(x / 5)) * 5) + ((x % 5) > 0 ? 5 : 0);
}
I was looking for this, but my example was to take a number, such as 4.2769 and drop it in a span as just 4.3. Not exactly the same, but if this helps:
Model.Statistics.AverageReview <= it's just a double from the model
Then:
#Model.Statistics.AverageReview.ToString("n1") <=gives me 4.3
#Model.Statistics.AverageReview.ToString("n2") <=gives me 4.28
etc...
Using Math.Round(number) rounds to the nearest whole number.
Use Math.Round:
double roundedValue = Math.Round(value, 0)
var roundedVal = Math.Round(2.5, 0);
It will give result:
var roundedVal = 3
If your working with integers rather than floating point numbers, here is the way.
#define ROUNDED_FRACTION(numr,denr) ((numr/denr)+(((numr%denr)<(denr/2))?0:1))
Here both "numr" and "denr" are unsigned integers.
Write your own round method. Something like,
function round(x)
rx = Math.ceil(x)
if (rx - x <= .000001)
return int(rx)
else
return int(x)
end
decimal RoundTotal = Total - (int)Total;
if ((double)RoundTotal <= .50)
Total = (int)Total;
else
Total = (int)Total + 1;
lblTotal.Text = Total.ToString();