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

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.

Related

Add two Decimal Values and Convert the Final value to INT

i am adding two decimal values like
decimal one=0; decimal two=0; decimal sum=0;
sum = one+ two;
Int final =0;
example
sum = 1.2 + 2.2;
sum = 3.4;
Now i want to save this 3.4 in Integer Final by neglecting that decimal part (.4). How can I do this?
class Program
{
static void Main(string[] args)
{
decimal one = 1.4M; decimal two = 3.4M; decimal sum = 0;
sum = one + two;
Int32 final = (Int32)(sum);
Int32 roundfinal = (Int32)(Math.Round(sum));
Console.WriteLine("final is "+ final);
Console.WriteLine("roundfinal is " + roundfinal);
Console.ReadLine();
}
}
check the answer without round rumber and with round number 4.8 is 4 without round and 4.8 round is 5
What you're looking for!:
final = Convert.ToInt32(sum);
Or:
final = (int)sum;
Decimal value = Decimal.Add(a1, a2);
FinalOutout int = Convert.ToInt32(value);
It will work.

String/Int to double with precision defined onruntime

I have an input type integer that represents a number that needs to be converted to double between 1-100, and the rest is decimal precision.
Example: 1562 -> 15.62 ; 198912 -> 19.8912
Right now, I tried a conversion to string, count the number of characters, take 2 to check how many decimals I have and depending of the result "create" a composite string to get a valid double...
Any idea of there is a better way of resolving convert-precision on runtime.
What about this:
int value = 1562;
decimal d = value;
while (d > 100) {
d /= 10;
}
You can use LINQ Skip and Take like:
string str = "198912";
string newStr = string.Format("{0}.{1}", new string(str.Take(2).ToArray()), new string(str.Skip(2).ToArray()));
double d = double.Parse(newStr, CultureInfo.InvariantCulture);
You can add the checks for length on original string, and also use double.TryParse to see if you get valid values.
If you have an int to begin with then you can use decimal, which would provide you more accurate conversion. Like:
int number = 1562123123;
decimal decimalNumber = number;
while (decimalNumber > 100)
{
decimalNumber /= 10;
}
Here is a mathematical solution. The line lg = Math.Max(lg, 0); changes "2" to return "2.0" instead of "20.0" but I guess that depends on your needs for single digit numbers.
static double ToDoubleBetween1And100(int num)
{
var lg = Math.Floor(Math.Log10(num)) - 1;
lg = Math.Max(lg, 0);
return ((double)num) / Math.Pow(10, lg);
}

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.

How to display just first 2 decimals unequal to 0

How can I display the number with just the 2 not=zero decimals?
Example:
For 0.00045578 I want 0.00045 and for 1.0000533535 I want 1.000053
There is no built in formatting for that.
You can get the fraction part of the number and count how many zeroes there are until you get two digits, and put together the format from that. Example:
double number = 1.0000533535;
double i = Math.Floor(number);
double f = number % 1.0;
int cnt = -2;
while (f < 10) {
f *= 10;
cnt++;
}
Console.WriteLine("{0}.{1}{2:00}", i, new String('0', cnt), f);
Output:
1.000053
Note: The given code only works if there actually is a fractional part of the number, and not for negative numbers. You need to add checks for that if you need to support those cases.
My solution would be to convert the number to a string. Search for the ".", then count zeroes till you find a non-zero digit, then take two digits.
It's not an elegant solution, but I think it will give you consistent results.
Try this function, using parsing to find the # of fractional digits rather than looking for zeros (it works for negative #s as well):
private static string GetTwoFractionalDigitString(double input)
{
// Parse exponential-notation string to find exponent (e.g. 1.2E-004)
double absValue = Math.Abs(input);
double fraction = (absValue - Math.Floor(absValue));
string s1 = fraction.ToString("E1");
// parse exponent peice (starting at 6th character)
int exponent = int.Parse(s1.Substring(5)) + 1;
string s = input.ToString("F" + exponent.ToString());
return s;
}
You can use this trick:
int d, whole;
double number = 0.00045578;
string format;
whole = (int)number;
d = 1;
format = "0.0";
while (Math.Floor(number * Math.Pow(10, d)) / Math.Pow(10, d) == whole)
{
d++;
format += "0";
}
format += "0";
Console.WriteLine(number.ToString(format));

Categories