Add two Decimal Values and Convert the Final value to INT - c#

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.

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");

Convert double to long without truncating

How to convert a double to a long without truncating it?
For example,
I want -26.3999745 to become -263999745
So far the methods I have tried such as Convert.ToInt64() truncate the number.
EDIT:
The number of decimal places varies, some of the numbers may have 5 decimal places
If you are really sure this is what you really want ..
long.Parse((-26.3999745).ToString().Replace(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator.ToString(), string.Empty)))
Following 2 steps
Get the numbers after the decimal n
Multiply by 10^n
Code:
double number = -26.3999745;
int n = BitConverter.GetBytes(decimal.GetBits((decimal)number)[3])[2];
long result = (long)(number * Math.Pow(10, n));
If you like to follow Single Responsibility (you should), then you can go with a second approach that is also not culture specific:
static int GetCountAfterDecimal(double number)
{
int count = 0;
string seperator = System.Globalization.CultureInfo.CurrentCulture
.NumberFormat.NumberDecimalSeparator;
string numberAsString = number.ToString();
int indexOfSeperator = numberAsString.IndexOf(seperator);
if (indexOfSeperator >= 0)
count = numberAsString.Length - indexOfSeperator - 1;
return count;
}
static long RemoveDecimalPoint(double number, int numbersCountAfterDecimal)
{
return (long)(number * Math.Pow(10, numbersCountAfterDecimal));
}
static void Main(string[] args)
{
double number = -26.3999745;
long result = RemoveDecimalPoint(number, GetCountAfterDecimal(number));
Console.WriteLine(result);
}
This might do the trick for you
double YourNumber = -26.3999745;
int DecimalPlacesCount = BitConverter.GetBytes(decimal.GetBits(Convert.ToDecimal(YourNumber))[3])[2];
long number = Convert.ToInt64("1".PadRight(DecimalPlacesCount + 1, '0'));
long kajs = (long) (YourNumber * number);

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.

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.

How do I round doubles in human-friendly manner in C#?

In my C# program I have a double obtained from some computation and its value is something like 0,13999 or 0,0079996 but this value has to be presented to a human so it's better displayed as 0,14 or 0,008 respectively.
So I need to round the value, but have no idea to which precision - I just need to "throw away those noise digits".
How could I do that in my code?
To clarify - I need to round the double values to a precision that is unknown at compile time - this needs to be determined at runtime. What would be a good heuristic to achieve this?
You seem to want to output a value which is not very different to the input value, so try increasing numbers of digits until a given error is achieved:
static double Round(double input, double errorDesired)
{
if (input == 0.0)
return 0.0;
for (int decimals = 0; decimals < 17; ++decimals)
{
var output = Math.Round(input, decimals);
var errorAchieved = Math.Abs((output - input) / input);
if (errorAchieved <= errorDesired)
return output;
}
return input;
}
}
static void Main(string[] args)
{
foreach (var input in new[] { 0.13999, 0.0079996, 0.12345 })
{
Console.WriteLine("{0} -> {1} (.1%)", input, Round(input, 0.001));
Console.WriteLine("{0} -> {1} (1%)", input, Round(input, 0.01));
Console.WriteLine("{0} -> {1} (10%)", input, Round(input, 0.1));
}
}
private double PrettyRound(double inp)
{
string d = inp.ToString();
d = d.Remove(0,d.IndexOf(',') + 1);
int decRound = 1;
bool onStartZeroes = true;
for (int c = 1; c < d.Length; c++ )
{
if (!onStartZeroes && d[c] == d[c - 1])
break;
else
decRound++;
if (d[c] != '0')
onStartZeroes = false;
}
inp = Math.Round(inp, decRound);
return inp;
}
Test:
double d1 = 0.13999; //no zeroes
double d2 = 0.0079996; //zeroes
double d3 = 0.00700956; //zeroes within decimal
Response.Write(d1 + "<br/>" + d2 + "<br/>" + d3 + "<br/><br/>");
d1 = PrettyRound(d1);
d2 = PrettyRound(d2);
d3 = PrettyRound(d3);
Response.Write(d1 + "<br/>" + d2 + "<br/>" + d3 +"<br/><br/>");
Prints:
0,13999
0,0079996
0,00700956
0,14
0,008
0,007
Rounds your numbers as you wrote in your example..
I can think of a solution though it isn't very efficient...
My assumption is that you can tell when a number is in the "best" human readable format when extra digits make no difference to how it is rounded.
eg in the example of 0,13999 rounding it to various numbers of decimal places gives:
0
0.1
0.14
0.14
0.14
0.13999
I'd suggest that you could loop through and detect that stable patch and cut off there.
This method seems to do this:
public double CustomRound(double d)
{
double currentRound = 0;
int stability = 0;
int roundLevel = 0;
while (stability < 3)
{
roundLevel++;
double current = Math.Round(d, roundLevel);
if (current == currentRound)
{
stability++;
}
else
{
stability = 1;
currentRound=current;
}
}
return Math.Round(d, roundLevel);
}
This code might be cleanable but it does the job and is a sufficient proof of concept. :)
I should emphasise that that initial assumption (that no change when rounding) is the criteria we are looking at which means that something like 0.3333333333 will not get rounded at all. With the examples given I'm unable to say if this is correct or not but I assume if this is a double issues that the problem is with the very slight variations from the "right" value and the value as a double.
Heres what I tried:
public decimal myRounding(decimal number)
{
double log10 = Math.Log10((double) number);
int precision = (int)(log10 >= 0 ? 0 : Math.Abs(log10)) + (number < 0.01m ? 1 : 2);
return Math.Round(number, precision);
}
test:
Console.WriteLine(myRounding(0.0000019999m)); //0.000002
Console.WriteLine(myRounding(0.0003019999m)); //0.0003
Console.WriteLine(myRounding(2.56777777m)); //2.57
Console.WriteLine(myRounding(0.13999m)); //0.14
Console.WriteLine(myRounding(0.0079996m)); //0.008
You can do it without converting to string. This is what I created fast:
private static double RoundDecimal(double number)
{
double temp2 = number;
int temp, counter = 0;
do
{
temp2 = 10 * temp2;
temp = (int)temp2;
counter++;
} while (temp < 1);
return Math.Round(number, counter < 2 ? 2 : counter);
}
or
private static double RoundDecimal(double number)
{
int counter = 0;
if (number > 0) {
counter = Math.Abs((int) Math.Log10(number)) + 1;
return Math.Round(arv, counter < 2 ? 2 : counter);
}
After giving it another thought I did the following and looks like it does what I want so far.
I iterate over the number of digits and compare Round( value, number ) and Round( value, number + 1 ). Once they are equal (not == of course - I compare the difference against a small number) then number is the number of digits I'm looking for.
Double.ToString() can take a string format as an argument. This will display as many characters as you require, rounding to the decimal place. E.G:
double Value = 1054.32179;
MessageBox.Show(Value.ToString("0.000"));
Will display "1054.322".
Source
Generic formats (i.e, pre-generated)
How to generate custom formats
You can use no of digits with Math.Round Function
Double doubleValue = 4.052102;
Math.Round(doubleValue, 2);
This will return 4.05 as your required answer.
This is tested code, can u explain me how i am wrong. So i need to change.

Categories