decimal round off: why? - c#

string a = "9.42";
string b = "1610.25";
decimal aa = decimal.Parse(a, CultureInfo.InvariantCulture);
decimal bb = decimal.Parse(b, CultureInfo.InvariantCulture);
decimal res = decimal.Multiply(aa, bb);
string res2 = res.ToString("#0.00", CultureInfo.CreateSpecificCulture("sv-SE"));
Result
//res = 15168.555
//res2 = "15168,56"
I want output res2=15168,55. How to achive it?

The default rounding method is to round a midpoint value to the closest even decimal, e.g. 1.555 is rounded to 1.56 but 1.585 is rounded to 1.58.
You can use the Math.Floor method to round down, but it doesn't have an overload where you can specify the number of decimal places, so you need to multiply and divide:
res = Math.Floor(res * 100m) / 100m;

string res2 = (Math.Floor(res * 100) / 100).ToString();

Related

C# Padding Decimal Points

I want to pad my number decimal points to 6.
So 0.0345 --> become 0.034500
0.6 --> become 0.600000
But no matter what decimal values I put in Math.Round, my code below only pads the decimal points to 5
var amount = Math.Round(0.0345, 6, MidpointRounding.AwayFromZero);
var amount1 = Math.Round(0.0345, 7, MidpointRounding.AwayFromZero);
Result:
amount = 0.03450
amount1 = 0.03450
Thank you.
There are two possibilities; if amount is of type decimal, you can add zero:
decimal amount = 0.0345m;
amount += 0.000000m;
Console.Write(amount);
Outcome:
0.034500
Or represent amount in desired format:
decimal amount = 0.0345m;
Console.Write(amount.ToString("F6"));
If amount is of type double or float then 0.034500 == 0.0345 and all you can do is to format when representing amount as a string:
double amount = 0.0345;
...
// F6 format string stands for 6 digits after the decimal point
Console.Write(amount.ToString("F6"));
Edit: In order create such kind of zero you can use
public static decimal Zero(int zeroesAfterDecimalPoint) {
if (zeroesAfterDecimalPoint < 0 || zeroesAfterDecimalPoint > 29)
throw new ArgumentOutOfRangeException(nameof(zeroesAfterDecimalPoint));
int[] bits = new int[4];
bits[3] = zeroesAfterDecimalPoint << 16;
return new decimal(bits);
}
And so have MyRound method:
private static Decimal MyRound(Decimal value, int digits) {
return Math.Round(value, digits, MidpointRounding.AwayFromZero) +
Zero(digits);
}
private static Decimal MyRound(double value, int digits) =>
MyRound((decimal)value, digits);
...
decimal amount = 0.0345m;
Console.WriteLine(MyRound(amount, 6));
Console.WriteLine(MyRound(0.0345, 7)); // let's provide double and 7 digits
Outcome:
0.034500
0.0345000
You can simply use format string with six decimals
decimal value = 0.6m;
Console.WriteLine("{0:0.000000}", value);
value = 0.0345m;
Console.WriteLine("{0:0.000000}", value);
// output
// 0.600000
// 0.034500
It only works this way if the incoming value is double.
double doubleParsing = 0.0345;
decimal amount = decimal.Parse(doubleParsing.ToString());
amount += 0.000000m;
var result = amount.ToString("F5");

C# Math.Round() on periodic doubles [duplicate]

I want to round my decimal value like 2.2222 to 2.23. When I use round,
decimal a = Math.Round((decimal)2.222, 2);
When I use ceiling, it cause 3
decimal c = Math.Ceiling((decimal)2.22);
How can I get 2.2222 to 2.23 ?
public static decimal CeilingAfterPoint(this decimal number, int digitsAfterPoint) {
return Math.Ceiling(number * (decimal)Math.Pow(10, digitsAfterPoint))
/ (decimal)Math.Pow(10, digitsAfterPoint);
}
Legacy question. But it deserves a right answer. Since .net core 3 you have been able to round decimals the following way:
Decimal.Round(2.222m, 2, MidpointRounding.ToPositiveInfinity);
It rounds upwards for the 2nd decimal.
MidpointRounding Docs
decimal c = Math.Ceiling((decimal)2.2222*100)/100;
but it's stupid.
try something like
decimal c = Math.Ceiling((decimal)2.222*100)/100;
but it fails if your value is 2.22
I solved my problem..
string n = "2.2222";
string[] s = n.Split('.');
if (s[1].Count() >= 3)
{
List<char> z = s[1].ToString().Take(2).ToList();
int c=Convert.ToInt32(z[0].ToString() + z[1].ToString()) + 1;
// int b = Convert.ToInt32(s[1].ElementAt(0).ToString() + s[1].ElementAt(1).ToString()) + 1;
string output= s[0] + "." + c.ToString();
}
now any number can put ,it will take 2 decimal value and add 1.Thanks.

Rounding of decimal in c# seems wrong

This part of code should speak for itself, my question is can I get 1242.08 result in res variable, and not 1242.07, because in math
b = 1/(1/b)
and in double which has less precision it seems I got good result
Can I fix decimal part of calculation to give me mathematically right result:
decimal rate = 124.2075M;
decimal amount = 10M;
decimal control = decimal.Round(rate * amount, 2); //it is 1242.08
//but
decimal res = decimal.Round(amount * (1 / (1 / rate)), 2);//1242.07 - should be 1242.08
decimal res1 = decimal.Round(amount * 124.2075M, 2);//1242.08 OK
/////////////////////////////////////////////////////////////
//while with double seems OK
double ratef = 124.2075;
double amountf = 10;
double resf = Math.Round(amountf * (1 / (1 / ratef)), 2);//1242.08 OK
double res1f = Math.Round(amountf * 124.2075, 2);//1242.08 OK
That's a limitation of the datatype decimal that can hold up to 29 digits
The result of the first calculation (res1) does not fit into decimal so you get a invalid/imprecisely result.
decimal rate = 124.2075M;
decimal amount = 10M;
decimal res1 = (1 / rate); //0.0080510436165287925447336111M <- not enough decimal places
decimal res2 = (1 / res1); //124.20749999999999999999999991M
decimal res3 = amount * res2; //1242.0749999999999999999999991M
decimal res4 = decimal.Round(res3, 2); //1242.07M <- correct rounding

C# decimal take ceiling 2

I want to round my decimal value like 2.2222 to 2.23. When I use round,
decimal a = Math.Round((decimal)2.222, 2);
When I use ceiling, it cause 3
decimal c = Math.Ceiling((decimal)2.22);
How can I get 2.2222 to 2.23 ?
public static decimal CeilingAfterPoint(this decimal number, int digitsAfterPoint) {
return Math.Ceiling(number * (decimal)Math.Pow(10, digitsAfterPoint))
/ (decimal)Math.Pow(10, digitsAfterPoint);
}
Legacy question. But it deserves a right answer. Since .net core 3 you have been able to round decimals the following way:
Decimal.Round(2.222m, 2, MidpointRounding.ToPositiveInfinity);
It rounds upwards for the 2nd decimal.
MidpointRounding Docs
decimal c = Math.Ceiling((decimal)2.2222*100)/100;
but it's stupid.
try something like
decimal c = Math.Ceiling((decimal)2.222*100)/100;
but it fails if your value is 2.22
I solved my problem..
string n = "2.2222";
string[] s = n.Split('.');
if (s[1].Count() >= 3)
{
List<char> z = s[1].ToString().Take(2).ToList();
int c=Convert.ToInt32(z[0].ToString() + z[1].ToString()) + 1;
// int b = Convert.ToInt32(s[1].ElementAt(0).ToString() + s[1].ElementAt(1).ToString()) + 1;
string output= s[0] + "." + c.ToString();
}
now any number can put ,it will take 2 decimal value and add 1.Thanks.

Printing numbers after decimal point

How can i print the numbers of a float/double variable after the decimal point?
For example for 435.5644 it will output 5644.
try with
fraction = value - (long) value;
or :
fraction = value - Math.Floor(value);
You can try the following:
double d = 435.5644;
int n = (int)d;
var v = d - n;
string s = string.Format("{0:#.0000}", v);
var result = s.Substring(1);
result: 5644
EDIT: reference to another question (http://stackoverflow.com/questions/4512306/get-decimal-part-of-a-number-in-javascript)
You can do the following:
double d = 435.5644;
float f = 435.5644f;
Console.WriteLine(Math.Round(d % 1, 4) * 10000);
Console.WriteLine(Math.Round(f % 1, 4) * 10000);
That will give you the integer part you looking for.
Best is to do it as Aghilas Yakoub answered, however, here below another option using string handling. Assuming all amounts will have decimals and that decimal separator is a dot (.) you just need to get the index 1.
double d = 435.5644;
Console.WriteLine(d.ToString().Split('.')[1]);
float f = 435.5644f;
Console.WriteLine(f.ToString().Split('.')[1]);
Otherwise you may get a Unhandled Exception: System.IndexOutOfRangeException.

Categories