Printing numbers after decimal point - c#

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.

Related

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.

Something is wrong with the accuracy of calculation between variables

I have some problems with my code where I think the accuracy is a bit off. I'll take out the declarations of variables from my code, so the code is as small as possible:
int a = Int32.Parse(tb_weight.Text);
double b = 0;
b = (a * 1.03) / 1000;
double g = 0;
g = (1.09 + (0.41 * (Math.Sqrt(50 / b))));
lbl_vertforce.Content = Math.Round((b * g * 9.81), 2);
So, tb_weight is a textbox where the input is made, and lets say the input is 5000, the label lbl_vertforce is showing 119,61 and according to my calculator, it should show 119,74. What is wroing here?
Doubles are not 100% precise and can vary in the least common digits. If you want exact precision you need to use Decimal type which has a bigger memory foot print, but was designed to be very precise. Unfortunately Math.Sqrt is not overloaded for Decimal and only works on doubles. I have provide code I found in another posting discussing the subject of Decimal Square roots: Performing Math operations on decimal datatype in C#?
public void YourCodeModifiedForDecimal()
{
int a = Int32.Parse(tb_weight.Text);
decimal b = 0;
b = (a* 1.03m) / 1000m;
decimal g = 0;
g = (1.09m + (0.41m * (Sqrt(50m / b))));
lbl_vertforce.Content = Math.Round((b* g * 9.81m), 2);
}
public static decimal Sqrt(decimal x, decimal? guess = null)
{
var ourGuess = guess.GetValueOrDefault(x / 2m);
var result = x / ourGuess;
var average = (ourGuess + result) / 2m;
if (average == ourGuess) // This checks for the maximum precision possible with a decimal.
return average;
else
return Sqrt(x, average);
}
You need to round g to 2 decimal places to get 119.74 in the final calculation.
g = Math.Round(1.09 + (0.41 * (Math.Sqrt(50 / b))), 2);

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# one number before floating point

I need to somehow get one number before floating point and value after that floating point. Example:
Before: 212.12345;
After: 2.12345
Any Ideas?
Assuming you have:
decimal x = 212.12345m;
you can use the modulo operator:
decimal result = x % 10;
Note that the number should be represented as a decimal if you care about the accurate value.
See also: Meaning of "%" operation in C# for the numeric type double
You can do like this:
public double GetFirst(double a)
{
double b = a / 10.0;
return (b - (int)b) * 10.0;
}
try this
double x = 1;
var y = x/10;
var z = (y % (Math.Floor(y))) * 10;
Try this code
string num = "15464612.12345";
string t = num.Split('.')[0];
num = t[t.Length-1].ToString() + "." + num.Split('.')[1];
my approach was to find the number 210, and substract it....
will work for any number as well as smaller then 10.
double f1 = 233.1234;
double f2 = f1 - (((int)f1 / 10) * 10);

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.

Categories