I want to do this using the Math.Round function
Here's some examples:
decimal a = 1.994444M;
Math.Round(a, 2); //returns 1.99
decimal b = 1.995555M;
Math.Round(b, 2); //returns 2.00
You might also want to look at bankers rounding / round-to-even with the following overload:
Math.Round(a, 2, MidpointRounding.ToEven);
There's more information on it here.
Try this:
twoDec = Math.Round(val, 2)
If you'd like a string
> (1.7289).ToString("#.##")
"1.73"
Or a decimal
> Math.Round((Decimal)x, 2)
1.73m
But remember! Rounding is not distributive, ie. round(x*y) != round(x) * round(y). So don't do any rounding until the very end of a calculation, else you'll lose accuracy.
Personally I never round anything. Keep it as resolute as possible, since rounding is a bit of a red herring in CS anyway. But you do want to format data for your users, and to that end, I find that string.Format("{0:0.00}", number) is a good approach.
Wikipedia has a nice page on rounding in general.
All .NET (managed) languages can use any of the common language run time's (the CLR) rounding mechanisms. For example, the Math.Round() (as mentioned above) method allows the developer to specify the type of rounding (Round-to-even or Away-from-zero). The Convert.ToInt32() method and its variations use round-to-even. The Ceiling() and Floor() methods are related.
You can round with custom numeric formatting as well.
Note that Decimal.Round() uses a different method than Math.Round();
Here is a useful post on the banker's rounding algorithm.
See one of Raymond's humorous posts here about rounding...
// convert upto two decimal places
String.Format("{0:0.00}", 140.6767554); // "140.67"
String.Format("{0:0.00}", 140.1); // "140.10"
String.Format("{0:0.00}", 140); // "140.00"
Double d = 140.6767554;
Double dc = Math.Round((Double)d, 2); // 140.67
decimal d = 140.6767554M;
decimal dc = Math.Round(d, 2); // 140.67
=========
// just two decimal places
String.Format("{0:0.##}", 123.4567); // "123.46"
String.Format("{0:0.##}", 123.4); // "123.4"
String.Format("{0:0.##}", 123.0); // "123"
can also combine "0" with "#".
String.Format("{0:0.0#}", 123.4567) // "123.46"
String.Format("{0:0.0#}", 123.4) // "123.4"
String.Format("{0:0.0#}", 123.0) // "123.0"
If you want to round a number, you can obtain different results depending on: how you use the Math.Round() function (if for a round-up or round-down), you're working with doubles and/or floats numbers, and you apply the midpoint rounding. Especially, when using with operations inside of it or the variable to round comes from an operation. Let's say, you want to multiply these two numbers: 0.75 * 0.95 = 0.7125. Right? Not in C#
Let's see what happens if you want to round to the 3rd decimal:
double result = 0.75d * 0.95d; // result = 0.71249999999999991
double result = 0.75f * 0.95f; // result = 0.71249997615814209
result = Math.Round(result, 3, MidpointRounding.ToEven); // result = 0.712. Ok
result = Math.Round(result, 3, MidpointRounding.AwayFromZero); // result = 0.712. Should be 0.713
As you see, the first Round() is correct if you want to round down the midpoint. But the second Round() it's wrong if you want to round up.
This applies to negative numbers:
double result = -0.75 * 0.95; //result = -0.71249999999999991
result = Math.Round(result, 3, MidpointRounding.ToEven); // result = -0.712. Ok
result = Math.Round(result, 3, MidpointRounding.AwayFromZero); // result = -0.712. Should be -0.713
So, IMHO, you should create your own wrap function for Math.Round() that fit your requirements. I created a function in which, the parameter 'roundUp=true' means to round to next greater number. That is: 0.7125 rounds to 0.713 and -0.7125 rounds to -0.712 (because -0.712 > -0.713). This is the function I created and works for any number of decimals:
double Redondea(double value, int precision, bool roundUp = true)
{
if ((decimal)value == 0.0m)
return 0.0;
double corrector = 1 / Math.Pow(10, precision + 2);
if ((decimal)value < 0.0m)
{
if (roundUp)
return Math.Round(value, precision, MidpointRounding.ToEven);
else
return Math.Round(value - corrector, precision, MidpointRounding.AwayFromZero);
}
else
{
if (roundUp)
return Math.Round(value + corrector, precision, MidpointRounding.AwayFromZero);
else
return Math.Round(value, precision, MidpointRounding.ToEven);
}
}
The variable 'corrector' is for fixing the inaccuracy of operating with floating or double numbers.
This is for rounding to 2 decimal places in C#:
label8.Text = valor_cuota .ToString("N2") ;
In VB.NET:
Imports System.Math
round(label8.text,2)
I know its an old question but please note for the following differences between Math round and String format round:
decimal d1 = (decimal)1.125;
Math.Round(d1, 2).Dump(); // returns 1.12
d1.ToString("#.##").Dump(); // returns "1.13"
decimal d2 = (decimal)1.1251;
Math.Round(d2, 2).Dump(); // returns 1.13
d2.ToString("#.##").Dump(); // returns "1.13"
Had a weird situation where I had a decimal variable, when serializing 55.50 it always sets default value mathematically as 55.5. But whereas, our client system is seriously expecting 55.50 for some reason and they definitely expected decimal. Thats when I had write the below helper, which always converts any decimal value padded to 2 digits with zeros instead of sending a string.
public static class DecimalExtensions
{
public static decimal WithTwoDecimalPoints(this decimal val)
{
return decimal.Parse(val.ToString("0.00"));
}
}
Usage should be
var sampleDecimalValueV1 = 2.5m;
Console.WriteLine(sampleDecimalValueV1.WithTwoDecimalPoints());
decimal sampleDecimalValueV1 = 2;
Console.WriteLine(sampleDecimalValueV1.WithTwoDecimalPoints());
Output:
2.50
2.00
One thing you may want to check is the Rounding Mechanism of Math.Round:
http://msdn.microsoft.com/en-us/library/system.midpointrounding.aspx
Other than that, I recommend the Math.Round(inputNumer, numberOfPlaces) approach over the *100/100 one because it's cleaner.
You should be able to specify the number of digits you want to round to using Math.Round(YourNumber, 2)
You can read more here.
Math.Floor(123456.646 * 100) / 100
Would return 123456.64
string a = "10.65678";
decimal d = Math.Round(Convert.ToDouble(a.ToString()),2)
public double RoundDown(double number, int decimalPlaces)
{
return Math.Floor(number * Math.Pow(10, decimalPlaces)) / Math.Pow(10, decimalPlaces);
}
Related
Decimal remembers its number of decimal places:
Console.WriteLine(1.1m); // 1.1
Console.WriteLine(1.10m); // 1.10
I am in a situation where I do not control the serialization (so I cannot use a more explicitly formatted stringify), but there is a requirement to output exactly 2 decimal places.
So, I am trying to force any decimal into the same value but with 2 decimal places.
var d = Decimal.Round(1.1m, 2, MidpointRounding.AwayFromZero); // Try to increase precision
Console.WriteLine(d); // Is 1.1, but I need 1.10
It is achievable with ToString("F") and then Decimal.Parse(). But is there a neater way than via ToString()?
In order to ensure/increase "precision" up to 2 digits after the decimal point you can add 0.00m:
1.1m + 0.00m == 1.10m
The same idea generalized:
private static decimal FormatOut(decimal value, int afterDecimal) {
// rounding up and adding 0.00…0 - afterDecimal zeroes
return Decimal.Round(value, afterDecimal, MidpointRounding.AwayFromZero) +
new decimal(0, 0, 0, false, (byte)afterDecimal);
}
...
decimal result = FormatOut(1.1m, 2);
// 1.10
Console.Write(result);
How can I round values to nearest integer?
For example:
1.1 => 1
1.5 => 2
1.9 => 2
"Math.Ceiling()" is not helping me. Any ideas?
See the official documentation for more. For example:
Basically you give the Math.Round method three parameters.
The value you want to round.
The number of decimals you want to keep after the value.
An optional parameter you can invoke to use AwayFromZero rounding. (ignored unless rounding is ambiguous, e.g. 1.5)
Sample code:
var roundedA = Math.Round(1.1, 0); // Output: 1
var roundedB = Math.Round(1.5, 0, MidpointRounding.AwayFromZero); // Output: 2
var roundedC = Math.Round(1.9, 0); // Output: 2
var roundedD = Math.Round(2.5, 0); // Output: 2
var roundedE = Math.Round(2.5, 0, MidpointRounding.AwayFromZero); // Output: 3
var roundedF = Math.Round(3.49, 0, MidpointRounding.AwayFromZero); // Output: 3
Live Demo
You need MidpointRounding.AwayFromZero if you want a .5 value to be rounded up. Unfortunately this isn't the default behavior for Math.Round(). If using MidpointRounding.ToEven (the default) the value is rounded to the nearest even number (1.5 is rounded to 2, but 2.5 is also rounded to 2).
Math.Ceiling
always rounds up (towards the ceiling)
Math.Floor
always rounds down (towards to floor)
what you are after is simply
Math.Round
which rounds as per this post
You need Math.Round, not Math.Ceiling. Ceiling always "rounds" up, while Round rounds up or down depending on the value after the decimal point.
there's this manual, and kinda cute way too:
double d1 = 1.1;
double d2 = 1.5;
double d3 = 1.9;
int i1 = (int)(d1 + 0.5);
int i2 = (int)(d2 + 0.5);
int i3 = (int)(d3 + 0.5);
simply add 0.5 to any number, and cast it to int (or floor it) and it will be mathematically correctly rounded :D
You can use Math.Round as others have suggested (recommended), or you could add 0.5 and cast to an int (which will drop the decimal part).
double value = 1.1;
int roundedValue = (int)(value + 0.5); // equals 1
double value2 = 1.5;
int roundedValue2 = (int)(value2 + 0.5); // equals 2
Just a reminder. Beware for double.
Math.Round(0.3 / 0.2 ) result in 1, because in double 0.3 / 0.2 = 1.49999999
Math.Round( 1.5 ) = 2
You have the Math.Round function that does exactly what you want.
Math.Round(1.1) results with 1
Math.Round(1.8) will result with 2.... and so one.
this will round up to the nearest 5 or not change if it already is divisible by 5
public static double R(double x)
{
// markup to nearest 5
return (((int)(x / 5)) * 5) + ((x % 5) > 0 ? 5 : 0);
}
I was looking for this, but my example was to take a number, such as 4.2769 and drop it in a span as just 4.3. Not exactly the same, but if this helps:
Model.Statistics.AverageReview <= it's just a double from the model
Then:
#Model.Statistics.AverageReview.ToString("n1") <=gives me 4.3
#Model.Statistics.AverageReview.ToString("n2") <=gives me 4.28
etc...
Using Math.Round(number) rounds to the nearest whole number.
Use Math.Round:
double roundedValue = Math.Round(value, 0)
var roundedVal = Math.Round(2.5, 0);
It will give result:
var roundedVal = 3
If your working with integers rather than floating point numbers, here is the way.
#define ROUNDED_FRACTION(numr,denr) ((numr/denr)+(((numr%denr)<(denr/2))?0:1))
Here both "numr" and "denr" are unsigned integers.
Write your own round method. Something like,
function round(x)
rx = Math.ceil(x)
if (rx - x <= .000001)
return int(rx)
else
return int(x)
end
decimal RoundTotal = Total - (int)Total;
if ((double)RoundTotal <= .50)
Total = (int)Total;
else
Total = (int)Total + 1;
lblTotal.Text = Total.ToString();
Ex, I have number 345.38, 2323.805555, 21.3333. I want to get the number after the decimal and round it up.
345.38 --> 4
2323.805555 --> 8
21.3333 --> 3
multiply by 10
ceiling (always rounds up, use 'round' to round down if lower than 0.5)
find the result of modding by 10
Like:
float myFloat = 123.38f;
float myBiggerFloat = Math.Ceiling(myFloat * 10.0f);
int theAnswer = ((int)myBiggerFloat % 10);
Or just ask for help for your homework on SO, either way seems to work.
This avoids potential overflow issues:
decimal value;
string[] sep = new[] { NumberFormatInfo.CurrentInfo.NumberDecimalSeparator };
String.Format("{0:0.0}", Math.Round(value, 1)).Split(sep, StringSplitOptions.None)[1][0];
This avoids string conversions and overflow issues:
decimal value;
decimal absValue = Math.Abs(value);
decimal fraction = absValue - Math.Floor(absValue);
int lastDigit = Convert.ToInt32(10 * Math.Round(fraction, 1));
If you just want the digit immediately following the decimal...couldn't you do something like this?
float value;
int digit = (int)(((value % 1) * 10) + 0.5)
Get the fractional part, multiply by ten, and round:
double n = 345.38;
int digit = (int)Math.Round((n - Math.Floor(n)) * 10);
This avoids any overflow issues, as the result is already down to one digit when cast to an int.
I have verified that this gives the desired result for your examples.
This whole overflow discussion is a little academic, and most likely not the intention of your homework. But should you want to solve that problem:
decimal value = -0.25m;
decimal fractionalPart = Math.Abs(value - Math.Truncate(value));
int digit = (int)Math.Round(10 * fractionalPart, MidpointRounding.AwayFromZero);
Edit: after reading your question again, I noticed that numbers shouldn't always be rounded up like my original answer. However, most people using Math.Round here use the default banker's rounding (to an even number). It depends if you intended -0.25 to result in 2 or 3. The way I'm reading your description, it should be 3 like in this example.
float myNum = 10.11;
char c = myNum[myNum.ToString().IndexOf(".") + 1];
How can i truncate the leading digit of double value in C#,I have tried Math.Round(doublevalue,2) but not giving the require result. and i didn't find any other method in Math class.
For example i have value 12.123456789 and i only need 12.12.
EDIT: It's been pointed out that these approaches round the value instead of truncating. It's hard to genuinely truncate a double value because it's not really in the right base... but truncating a decimal value is more feasible.
You should use an appropriate format string, either custom or standard, e.g.
string x = d.ToString("0.00");
or
string x = d.ToString("F2");
It's worth being aware that a double value itself doesn't "know" how many decimal places it has. It's only when you convert it to a string that it really makes sense to do so. Using Math.Round will get the closest double value to x.xx00000 (if you see what I mean) but it almost certainly won't be the exact value x.xx00000 due to the way binary floating point types work.
If you need this for anything other than string formatting, you should consider using decimal instead. What does the value actually represent?
I have articles on binary floating point and decimal floating point in .NET which you may find useful.
What have you tried? It works as expected for me:
double original = 12.123456789;
double truncated = Math.Truncate(original * 100) / 100;
Console.WriteLine(truncated); // displays 12.12
double original = 12.123456789;
double truncated = Truncate(original, 2);
Console.WriteLine(truncated.ToString());
// or
// Console.WriteLine(truncated.ToString("0.00"));
// or
// Console.WriteLine(Truncate(original, 2).ToString("0.00"));
public static double Truncate(double value, int precision)
{
return Math.Truncate(value * Math.Pow(10, precision)) / Math.Pow(10, precision);
}
How about:
double num = 12.12890;
double truncatedNum = ((int)(num * 100))/100.00;
This could work (although not tested):
public double RoundDown(this double value, int digits)
{
int factor = Math.Pow(10,digits);
return Math.Truncate(value * factor) / factor;
}
Then you simply use it like this:
double rounded = number.RoundDown(2);
This code....
double x = 12.123456789;
Console.WriteLine(x);
x = Math.Round(x, 2);
Console.WriteLine(x);
Returns this....
12.123456789
12.12
What is your desired result that is different?
If you want to keep the value as a double, and just strip of any digits after the second decimal place and not actually round the number then you can simply subtract 0.005 from your number so that round will then work. For example.
double x = 98.7654321;
Console.WriteLine(x);
double y = Math.Round(x - 0.005, 2);
Console.WriteLine(y);
Produces this...
98.7654321
98.76
There are a lot of answers using Math.Truncate(double).
However, the approach using Math.Truncate(double) can lead to incorrect results.
For instance, it will return 5.01 truncating 5.02, because multiplying of double values doesn't work precisely and 5.02*100=501.99999999999994
If you really need this precision, consider, converting to Decimal before truncating.
public static double Truncate(double value, int precision)
{
decimal power = (decimal)Math.Pow(10, precision);
return (double)(Math.Truncate((decimal)value * power) / power);
}
Still, this approach is ~10 times slower.
I'm sure there's something more .netty out there but why not just:-
double truncVal = Math.Truncate(val * 100) / 100;
double remainder = val-truncVal;
If you are looking to have two points after the decimal without rounding the number, the following should work
string doubleString = doublevalue.ToString("0.0000"); //To ensure we have a sufficiently lengthed string to avoid index issues
Console.Writeline(doubleString
.Substring(0, (doubleString.IndexOf(".") +1) +2));
The second parameter of substring is the count, and IndexOf returns to zero-based index, so we have to add one to that before we add the 2 decimal values.
This answer is assuming that the value should NOT be rounded
For vb.net use this extension:
Imports System.Runtime.CompilerServices
Module DoubleExtensions
<Extension()>
Public Function Truncate(dValue As Double, digits As Integer)
Dim factor As Integer
factor = Math.Pow(10, digits)
Return Math.Truncate(dValue * factor) / factor
End Function
End Module
I use a little formatting class that I put together which can add gaps and all sorts.
Here is one of the methods that takes in a decimal and return different amounts of decimal places based on the decimal display setting in the app
public decimal DisplayDecimalFormatting(decimal input, bool valueIsWeightElseMoney)
{
string inputString = input.ToString();
if (valueIsWeightElseMoney)
{
int appDisplayDecimalCount = Program.SettingsGlobal.DisplayDecimalPlacesCount;
if (appDisplayDecimalCount == 3)//0.000
{
inputString = String.Format("{0:#,##0.##0}", input, displayCulture);
}
else if (appDisplayDecimalCount == 2)//0.00
{
inputString = String.Format("{0:#,##0.#0}", input, displayCulture);
}
else if (appDisplayDecimalCount == 1)//0.0
{
inputString = String.Format("{0:#,##0.0}", input, displayCulture);
}
else//appDisplayDecimalCount 0 //0
{
inputString = String.Format("{0:#,##0}", input, displayCulture);
}
}
else
{
inputString = String.Format("{0:#,##0.#0}", input, displayCulture);
}
//Check if worked and return if worked, else return 0
bool itWorked = false;
decimal returnDec = 0.00m;
itWorked = decimal.TryParse(inputString, out returnDec);
if (itWorked)
{
return returnDec;
}
else
{
return 0.00m;
}
}
object number = 12.123345534;
string.Format({"0:00"},number.ToString());
When displaying the value of a decimal currently with .ToString(), it's accurate to like 15 decimal places, and since I'm using it to represent dollars and cents, I only want the output to be 2 decimal places.
Do I use a variation of .ToString() for this?
decimalVar.ToString("#.##"); // returns ".5" when decimalVar == 0.5m
or
decimalVar.ToString("0.##"); // returns "0.5" when decimalVar == 0.5m
or
decimalVar.ToString("0.00"); // returns "0.50" when decimalVar == 0.5m
I know this is an old question, but I was surprised to see that no one seemed to post an answer that;
Didn't use bankers rounding
Keeps the value as a decimal.
This is what I would use:
decimal.Round(yourValue, 2, MidpointRounding.AwayFromZero);
http://msdn.microsoft.com/en-us/library/9s0xa85y.aspx
decimalVar.ToString("F");
This will:
Round off to 2 decimal places eg. 23.456 → 23.46
Ensure that there
are always 2 decimal places eg. 23 → 23.00; 12.5 → 12.50
Ideal for displaying currency.
Check out the documentation on ToString("F") (thanks to Jon Schneider).
If you just need this for display use string.Format
String.Format("{0:0.00}", 123.4567m); // "123.46"
http://www.csharp-examples.net/string-format-double/
The "m" is a decimal suffix. About the decimal suffix:
http://msdn.microsoft.com/en-us/library/364x0z75.aspx
Given decimal d=12.345; the expressions d.ToString("C") or String.Format("{0:C}", d) yield $12.35 - note that the current culture's currency settings including the symbol are used.
Note that "C" uses number of digits from current culture. You can always override default to force necessary precision with C{Precision specifier} like String.Format("{0:C2}", 5.123d).
If you want it formatted with commas as well as a decimal point (but no currency symbol), such as 3,456,789.12...
decimalVar.ToString("n2");
There's a very important characteristic of Decimal that isn't obvious:
A Decimal 'knows' how many decimal places it has based upon where it came from
The following may be unexpected :
Decimal.Parse("25").ToString() => "25"
Decimal.Parse("25.").ToString() => "25"
Decimal.Parse("25.0").ToString() => "25.0"
Decimal.Parse("25.0000").ToString() => "25.0000"
25m.ToString() => "25"
25.000m.ToString() => "25.000"
Doing the same operations with Double will result in zero decimal places ("25") for all of the above examples.
If you want a decimal to 2 decimal places there's a high likelyhood it's because it's currency in which case this is probably fine for 95% of the time:
Decimal.Parse("25.0").ToString("c") => "$25.00"
Or in XAML you would use {Binding Price, StringFormat=c}
One case I ran into where I needed a decimal AS a decimal was when sending XML to Amazon's webservice. The service was complaining because a Decimal value (originally from SQL Server) was being sent as 25.1200 and rejected, (25.12 was the expected format).
All I needed to do was Decimal.Round(...) with 2 decimal places to fix the problem regardless of the source of the value.
// generated code by XSD.exe
StandardPrice = new OverrideCurrencyAmount()
{
TypedValue = Decimal.Round(product.StandardPrice, 2),
currency = "USD"
}
TypedValue is of type Decimal so I couldn't just do ToString("N2") and needed to round it and keep it as a decimal.
Here is a little Linqpad program to show different formats:
void Main()
{
FormatDecimal(2345.94742M);
FormatDecimal(43M);
FormatDecimal(0M);
FormatDecimal(0.007M);
}
public void FormatDecimal(decimal val)
{
Console.WriteLine("ToString: {0}", val);
Console.WriteLine("c: {0:c}", val);
Console.WriteLine("0.00: {0:0.00}", val);
Console.WriteLine("0.##: {0:0.##}", val);
Console.WriteLine("===================");
}
Here are the results:
ToString: 2345.94742
c: $2,345.95
0.00: 2345.95
0.##: 2345.95
===================
ToString: 43
c: $43.00
0.00: 43.00
0.##: 43
===================
ToString: 0
c: $0.00
0.00: 0.00
0.##: 0
===================
ToString: 0.007
c: $0.01
0.00: 0.01
0.##: 0.01
===================
Math.Round Method (Decimal, Int32)
Very rarely would you want an empty string if the value is 0.
decimal test = 5.00;
test.ToString("0.00"); //"5.00"
decimal? test2 = 5.05;
test2.ToString("0.00"); //"5.05"
decimal? test3 = 0;
test3.ToString("0.00"); //"0.00"
The top rated answer is incorrect and has wasted 10 minutes of (most) people's time.
Mike M.'s answer was perfect for me on .NET, but .NET Core doesn't have a decimal.Round method at the time of writing.
In .NET Core, I had to use:
decimal roundedValue = Math.Round(rawNumber, 2, MidpointRounding.AwayFromZero);
A hacky method, including conversion to string, is:
public string FormatTo2Dp(decimal myNumber)
{
// Use schoolboy rounding, not bankers.
myNumber = Math.Round(myNumber, 2, MidpointRounding.AwayFromZero);
return string.Format("{0:0.00}", myNumber);
}
None of these did exactly what I needed, to force 2 d.p. and round up as 0.005 -> 0.01
Forcing 2 d.p. requires increasing the precision by 2 d.p. to ensure we have at least 2 d.p.
then rounding to ensure we do not have more than 2 d.p.
Math.Round(exactResult * 1.00m, 2, MidpointRounding.AwayFromZero)
6.665m.ToString() -> "6.67"
6.6m.ToString() -> "6.60"
The top-rated answer describes a method for formatting the string representation of the decimal value, and it works.
However, if you actually want to change the precision saved to the actual value, you need to write something like the following:
public static class PrecisionHelper
{
public static decimal TwoDecimalPlaces(this decimal value)
{
// These first lines eliminate all digits past two places.
var timesHundred = (int) (value * 100);
var removeZeroes = timesHundred / 100m;
// In this implementation, I don't want to alter the underlying
// value. As such, if it needs greater precision to stay unaltered,
// I return it.
if (removeZeroes != value)
return value;
// Addition and subtraction can reliably change precision.
// For two decimal values A and B, (A + B) will have at least as
// many digits past the decimal point as A or B.
return removeZeroes + 0.01m - 0.01m;
}
}
An example unit test:
[Test]
public void PrecisionExampleUnitTest()
{
decimal a = 500m;
decimal b = 99.99m;
decimal c = 123.4m;
decimal d = 10101.1000000m;
decimal e = 908.7650m
Assert.That(a.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture),
Is.EqualTo("500.00"));
Assert.That(b.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture),
Is.EqualTo("99.99"));
Assert.That(c.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture),
Is.EqualTo("123.40"));
Assert.That(d.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture),
Is.EqualTo("10101.10"));
// In this particular implementation, values that can't be expressed in
// two decimal places are unaltered, so this remains as-is.
Assert.That(e.TwoDecimalPlaces().ToString(CultureInfo.InvariantCulture),
Is.EqualTo("908.7650"));
}
You can use system.globalization to format a number in any required format.
For example:
system.globalization.cultureinfo ci = new system.globalization.cultureinfo("en-ca");
If you have a decimal d = 1.2300000 and you need to trim it to 2 decimal places then it can be printed like this d.Tostring("F2",ci); where F2 is string formating to 2 decimal places and ci is the locale or cultureinfo.
for more info check this link
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
https://msdn.microsoft.com/en-us/library/dwhawy9k%28v=vs.110%29.aspx
This link explains in detail how you can handle your problem and what you can do if you want to learn more. For simplicity purposes, what you want to do is
double whateverYouWantToChange = whateverYouWantToChange.ToString("F2");
if you want this for a currency, you can make it easier by typing "C2" instead of "F2"
The most applicable solution is
decimalVar.ToString("#.##");
Double Amount = 0;
string amount;
amount=string.Format("{0:F2}", Decimal.Parse(Amount.ToString()));
If you need to keep only 2 decimal places (i.e. cut off all the rest of decimal digits):
decimal val = 3.14789m;
decimal result = Math.Floor(val * 100) / 100; // result = 3.14
If you need to keep only 3 decimal places:
decimal val = 3.14789m;
decimal result = Math.Floor(val * 1000) / 1000; // result = 3.147
var arr = new List<int>() { -4, 3, -9, 0, 4, 1 };
decimal result1 = arr.Where(p => p > 0).Count();
var responseResult1 = result1 / arr.Count();
decimal result2 = arr.Where(p => p < 0).Count();
var responseResult2 = result2 / arr.Count();
decimal result3 = arr.Where(p => p == 0).Count();
var responseResult3 = result3 / arr.Count();
Console.WriteLine(String.Format("{0:#,0.000}", responseResult1));
Console.WriteLine(String.Format("{0:#,0.0000}", responseResult2));
Console.WriteLine(String.Format("{0:#,0.00000}", responseResult3));
you can put as many 0 as you want.