Calculating with decimal - c#

I'm trying to get the comma number of my int after having calculated it, but i can't seem to get it to work.
My code:
int price = 120;
decimal calc = price / 100;
But it only returns 1.

int price = 120;
decimal calc = price / 100m;
your variant:
int price = 120;
int temp = price / 100;// temp = 1
decimal calc = (decimal) temp;

int price = 120;
decimal calc = ((decimal)price) / 100;

You canculation is being done in integer type as both the operands are integer. It should be:
decimal calc = price / 100M;
// ^^^^^
//atleast one of the operand should be decimal
Or
decimal calc = (decimal)price / 100;

When you divide an integer by another integer, result is always an integer. Since you want your answer in more precise way you need to typecast it based on precision that you want. Decimal gives you best possible precision in C#. But even casting to float or double would have also given you answer in the format that you expected. Casting again depends on level of accuracy needed. Here is more detailed explanation from MSDN.

The simplest way is declare price as decimal also
decimal price=120;
decimal calc=price/100;
If it is from an argument or another local variable, you can still store it in decimal like:
int priceInInt=120;
decimal price=priceInInt;
decimal calc=price/100;

Related

Why Math.Round doesn't always rounding doubles

int fieldGoals = int.Parse(Console.ReadLine());
int fieldGoalAttempts = int.Parse(Console.ReadLine());
int threePointFieldGoals = int.Parse(Console.ReadLine());
int turnovers = int.Parse(Console.ReadLine());
int offensiveRebounds = int.Parse(Console.ReadLine());
int opponentDefensiveRebounds = int.Parse(Console.ReadLine());
int freeThrows = int.Parse(Console.ReadLine());
int freeThrowAttempts = int.Parse(Console.ReadLine());
double eFG = Math.Round( (fieldGoals + 0.5 * threePointFieldGoals) / fieldGoalAttempts );
double TOV = Math.Round( turnovers / (fieldGoalAttempts + 0.44 * freeThrowAttempts + turnovers) );
double ORB = Math.Round( offensiveRebounds / (offensiveRebounds + opponentDefensiveRebounds) );
double FT = Math.Round( freeThrows / fieldGoalAttempts );
The problem is with double ORB and double FT.
For some reason I can't use Math.Round on them. It says that:
the call is ambiguous between the following methods or properties :
"Math.Round(double)" and "Math.Round(decimal)".
I just don't get it why the first two work but the second two don't.
In the first two calls, you added something to both. 0.5 and 0.44 both convert the values to doubles, because 0.5 and 0.44 are both considered doubles. But when you use the second two, they are both only using integers, which are neither double nor decimal, and which can be converted to either. To solve this you simply need to do Math.Round( (double) (*calculations*) );
Alternatively, and in fact the better way to do it would be to convert one of the values to double - that way, it would calculate the division in double.
(double)offensiveRebounds / (offensiveRebounds + opponentDefensiveRebounds)
(double)freeThrows / fieldGoalAttempts
You are calling Math.Round with int values. You probably want to convert them to double first:Math.Round( 1.0 * freeThrows...).
There is no Math.Round(int) overloaod, but there are overloads for double and decimal and int can be imlicitely converted to both. Therefore the call would be ambiguous.
You try to devide integer numbers - the result will be integer. So, you cant round this number. Convert it to double before devision and rounding:
double ORB = Math.Round( (double)offensiveRebounds / (offensiveRebounds + opponentDefensiveRebounds) );
double FT = Math.Round( (double)freeThrows / fieldGoalAttempts );
In the first two you have implicitly converted the argument to Math.Round to a double with the double (i.e. 0.5 and 0.44) used as the multiplication factor.
In the second two, you have not.

How to round up or down in C#?

I have tried using Math.Round & MidpointRounding. This does not appear to do what I need.
Example:
52.34567 rounded to 2 decimals UP = 52.35
1.183 rounded to 2 decimals DOWN = 1.18
Do I need to write a custom function?
Edit:
I should have been more specific.
Sometimes I need a number like 23.567 to round DOWN to 23.56.
In this scenario...
Math.Round(dec, 2, MidpointRounding.AwayFromZero) gives 23.57
Math.Round(dec, 2, MidpointRounding.ToEven) gives 23.57
Decimals up to 9 decimal places could come out and need to be rounded to 1, 2, 3 or even 4 decimal places.
Try using decimal.Round():
decimal.Round(x, 2)
Where x is your value and 2 is the number of decimals you wish to keep.
You can also specify whether .5 rounds up or down by passing third parameter:
decimal.Round(x, 2, MidpointRounding.AwayFromZero);
EDIT:
In light of the new requirement (i.e. that numbers are sometimes rounded down despite being greater than "halfway" to the next interval), you can try:
var pow = Math.Pow(10, numDigits);
var truncated = Math.Truncate(x*pow) / pow;
Truncate() lops off the non-integer portion of the decimal. Note that numDigits above should be how many digits you want to KEEP, not the total number of decimals, etc.
Finally, if you want to force a round up (truncation really is a forced round-down), you would just add 1 to the result of the Truncate() call before dividing again.
Try using Math.Ceiling (up) or Math.Floor (down). e.g Math.Floor(1.8) == 1.
Assuming you're using the decimal type for your numbers,
static class Rounding
{
public static decimal RoundUp(decimal number, int places)
{
decimal factor = RoundFactor(places);
number *= factor;
number = Math.Ceiling(number);
number /= factor;
return number;
}
public static decimal RoundDown(decimal number, int places)
{
decimal factor = RoundFactor(places);
number *= factor;
number = Math.Floor(number);
number /= factor;
return number;
}
internal static decimal RoundFactor(int places)
{
decimal factor = 1m;
if (places < 0)
{
places = -places;
for (int i = 0; i < places; i++)
factor /= 10m;
}
else
{
for (int i = 0; i < places; i++)
factor *= 10m;
}
return factor;
}
}
Example:
Rounding.RoundDown(23.567, 2) prints 23.56
For a shorter version of the accepted answer, here are the RoundUp and RoundDown functions that can be used:
public double RoundDown(double number, int decimalPlaces)
{
return Math.Floor(number * Math.Pow(10, decimalPlaces)) / Math.Pow(10, decimalPlaces);
}
public double RoundUp(double number, int decimalPlaces)
{
return Math.Ceiling(number * Math.Pow(10, decimalPlaces)) / Math.Pow(10, decimalPlaces);
}
Complete code with result.
double a = Math.Round(128.5, 0, MidpointRounding.AwayFromZero);
Result is 129
The Math class gives you methods to use to round up and down, they are Math.Ceiling() and Math.Floor() respectively. They work like Math.Round(), but they have a particularity, they only receive a value and round them to only the entire part.
So you need to use Math.Pow() to multiply the value by 10 to the n-esimal units you need to round power and then you need to divide by the same multiplied value.
Is important that you note, that the input parameters of the Math.Pow() method are double, so you need to convert them to double.
For example:
When you want to round up the value to 3 decimals (supposing value type is decimal):
double decimalsNumber = 3;
decimal valueToRound = 1.1835675M;
// powerOfTen must be equal to 10^3 or 1000.
double powerOfTen = Math.Pow(10, decimalsNumber);
// rounded must be equal to Math.Ceiling(1.1835675 * 1000) / 1000
decimal rounded = Math.Ceiling(valueToRound * (decimal)powerOfTen) / (decimal)powerOfTen;
Result: rounded = 1.184
When you want to round down the value to 3 decimals (supposing value type is decimal):
double decimalsNumber = 3;
decimal valueToRound = 1.1835675M;
// powerOfTen must be equal to 10^3 or 1000.
double powerOfTen = Math.Pow(10, decimalsNumber);
// rounded must be equal to Math.Floor(1.1835675 * 1000) / 1000
decimal rounded = Math.Floor(valueToRound * (decimal)powerOfTen) / (decimal)powerOfTen;
Result: rounded = 1.183
To reference how to use them more specificaly and to get more information and about both methods you can see these pages from the oficial MSDN Microsoft site:
Math Class
Math.Pow Method (Double, Double)
Math.Floor Method (Decimal)
Math.Floor Method (Double)
Math.Ceiling Method (Decimal)
Math.Ceiling Method (Double)
try this custom rounding
public int Round(double value)
{
double decimalpoints = Math.Abs(value - Math.Floor(value));
if (decimalpoints > 0.5)
return (int)Math.Round(value);
else
return (int)Math.Floor(value);
}
Maybe this?
Math.Round(dec + 0.5m, MidpointRounding.AwayFromZero);
You can achieve that by using the Method of Math.Round() or decimal.Round()-:
Math.Round(amt)
Math.Round(amt, Int32) and other overloading methods.
decimal.Round(amt)
decimal.Round(amt, 2) and other overloding methods.

Split decimal variable into integral and fraction parts

I am trying to extract the integral and fractional parts from a decimal value (both parts should be integers):
decimal decimalValue = 12.34m;
int integral = (int) decimal.Truncate(decimalValue);
int fraction = (int) ((decimalValue - decimal.Truncate(decimalValue)) * 100);
(for my purpose, decimal variables will contain up to 2 decimal places)
Are there any better ways to achieve this?
decimal fraction = (decimal)2.78;
int iPart = (int)fraction;
decimal dPart = fraction % 1.0m;
Try mathematical definition:
var fraction = (int)(100.0m * (decimalValue - Math.Floor(decimalValue)));
Although, it is not better performance-wise but at least it works for negative numbers.
decimal fraction = doubleNumber - Math.Floor(doubleNumber)
or something like that.
How about:
int fraction = (int) ((decimalValue - integral) * 100);
For taking out fraction you can use this solution:
Math.ceil(((f < 1.0) ? f : (f % Math.floor(f))) * 10000)

C#: divide an int by 100

How do I divide an int by 100?
eg:
int x = 32894;
int y = 32894 / 100;
Why does this result in y being 328 and not 328.94?
When one integer is divided by another, the arithmetic is performed as integer arithmetic.
If you want it to be performed as float, double or decimal arithmetic, you need to cast one of the values appropriately. For example:
decimal y = ((decimal) x) / 100;
Note that I've changed the type of y as well - it doesn't make sense to perform decimal arithmetic but then store the result in an int. The int can't possibly store 328.94.
You only need to force one of the values to the right type, as then the other will be promoted to the same type - there's no operator defined for dividing a decimal by an integer, for example. If you're performing arithmetic using several values, you might want to force all of them to the desired type just for clarity - it would be unfortunate for one operation to be performed using integer arithmetic, and another using double arithmetic, when you'd expected both to be in double.
If you're using literals, you can just use a suffix to indicate the type instead:
decimal a = x / 100m; // Use decimal arithmetic due to the "m"
double b = x / 100.0; // Use double arithmetic due to the ".0"
double c = x / 100d; // Use double arithmetic due to the "d"
double d = x / 100f; // Use float arithmetic due to the "f"
As for whether you should be using decimal, double or float, that depends on what you're trying to do. Read my articles on decimal floating point and binary floating point. Usually double is appropriate if you're dealing with "natural" quantities such as height and weight, where any value will really be an approximation; decimal is appropriate with artificial quantities such as money, which are typically represented exactly as decimal values to start with.
328.94 is not an integer. Integer / divide rounds down; that is how it works.
I suggest you cast to decimal:
decimal y = 32894M / 100;
or with variables:
decimal y = (decimal)x / 100;
Because an int is only a whole number. Try this instead.
int x = 32894;
double y = x / 100.0;
Because you're doing integer division. Add a period behind the 100 and you'll get a double instead.
When you divide two integers, the result is an integer. Integers don't have decimal places, so they're just truncated.
its programming fundamental that int(integer) dividing is different from float(floating point) dividing.
if u want .94 use float or double
var num = 3294F/100F

how to take 6 numbers after the dot - but without round the number?

how to take 6 numbers after the dot - but without round the number ?
for example:
102.123456789 => 102.123456
9.99887766 => 9.998877
in C# winforms
thak's in advance
You can use the Math.Truncate method and a 10^6 multiplier:
decimal x = 102.12345689m;
decimal m = 1000000m;
decimal y = Math.Truncate(m * x) / m;
Console.WriteLine(y); // Prints 102.123456
System.Math.Truncate (102.123456789 * factor) / factor;
In your case factor is 10^6; read more
public decimal TruncateDecimal(decimal decimalToTruncate, uint numberOfDecimalPlacse)
{
decimal multiplication_factor = (decimal)Math.Pow(10.0, numberOfDecimalPlacse);
decimal truncated_value = (long)(multiplication_factor * decimalToTruncate);
return (truncated_value / multiplication_factor);
}
I know this is ugly using strings, but thought I'd put it anyway:
double x = 9.9887766;
string[] xs = x.ToString().Split('.');
double result = double.Parse(xs[0] + "." + xs[1].Substring(0, Math.Min(xs[1].Length, 6)));
Might be a long winded way, but how about turning it into a string, locating the decimal point and then grabbing the string minus anything after the 6th decimal place. You could then turn it back into a decimal.
It's crude but how about:
decimal Number = 102.123456789;
string TruncateTarget = Number.ToString();
decimal FinalValue = Decimal.Parse(TruncateTarget.Substring(0, TruncateTarget.IndexOf('.') +6));

Categories