i want to parse like:
3.5 -> 3.5
3.484 -> 3.48
3.82822 -> 3.82
etc.
However,
decimal.Parse("3.543")
yields 3543 and
so i did:
decimal.Parse("3.543",CultureInfo.InvariantCulture)
yields 3.543 and
but
decimal.Parse(String.Format("{0:0.00}","3.543"),CultureInfo.InvariantCulture);
yields 3543
so how can i do it???
You need Round method:
decimal t = 3.82822;
decimal.Round(t, 2);
Where 2 show the decimal points you need.
Use Math.Round like this:
decimal a = 1.9946456M;
Math.Round(a, 2); //returns 1.99
decimal b = 1.9953454M;
Math.Round(b, 2); //returns 2.00
I guess you want to truncate the decimal places after two digits. Give this a try:
public decimal TruncateDecimal(decimal value, int precision)
{
decimal step = (decimal)Math.Pow(10, precision);
int tmp = (int)Math.Truncate(step * value);
return tmp / step;
}
decimal t = 3.82822;
decimal d = TruncateDecimal(t, 2);
You should use a culture that actually uses a comma as a decimal seperator.
CultureInfo.GetCultureInfo("fr-fr")
for example.
Console.WriteLine(decimal.Parse("3,543", CultureInfo.InvariantCulture)); // 3543
Console.WriteLine(decimal.Parse("3,543", CultureInfo.GetCultureInfo("fr-fr"))); //3,543
and if you want to round the result. You could use
Console.WriteLine(String.Format("{0:0.00}", decimal.Parse("3,543", CultureInfo.GetCultureInfo("fr-fr")))); //3,54
Related
I want to add precision to the decimal value. For example, I have this value:
decimal number = 10;
I want to make it 10.00. I don't want to convert it to string like number.ToString("#.00")
Currently, I have this method:
decimal CalculatePrecision(decimal value, int precision)
{
var storedCalculated = decimal.Divide(1, Convert.ToDecimal(Math.Pow(10, precision)));
return value + storedCalculated - storedCalculated;
}
Is there any good solution for this?
You can't. 10 and 10.00 are the same number. Only the "presentation" is different. Both "presentations" are strings. The actual number look different. If you need to change the presentation, convert to string.
How about
decimal d = 10;
d += 0.00M;
Console.WriteLine(d);
Try reference
Math.Round not keeping the trailing zero
How do I display a decimal value to 2 decimal places?
I have a double value: 0.314285 which I want to Round off to 5 decimal places. From a mathematical point of view my expectant result is: 0.31429. In my code I use the Math.Round with MidPointRounding.AwayFromZero parameter overload, the resultant output being: 0.31428.
Is there another way to implement to have the output result as: 0.31429??
You should read the rounding and precision article. The real representation of your number in memory can be something like 0.3142849999999999, and therefore you are getting 0.31428 result. Using a decimal type can help to solve this issue
var value = 0.314285m;
var result = Math.Round(value, 5, MidpointRounding.AwayFromZero); //0.31429
public static double RoundUp(double i, int decimalPlaces)
{
var power = Math.Pow(10, decimalPlaces);
return Math.Ceiling(i * power) / power;
}
RoundDown(0.314285, 5); //0.31429
Math.Round(decimal number to round, int number of decimal places)
I think this should work for what you are trying to do.
I have a timespan that displays as such: 7.43053333333333. My goal is to simply display it as 7.43.
How would I truncate two the second value after the decimal place. I tried using Math.Round instead of truncating, but it would simnple return 7
Just use Math.Round Method (Decimal, Int32)
double d = 7.43053333333333;
double ma = Math.Round(d, 2);
Use Math.Round and supply number of digits to round
double roundedValue = Math.Round(7.43053333333333, 2);
You will get back 7.43
How would I truncate two the second value after the decimal place.
if you just want to truncate the double value to get 2 digits after precision.
Try This:
double d = 7.43053333333333;
String s = d.ToString("N2");
use Math.Round() like following
Math.Round(7.43053333333333, 2);
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.
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));