How to round a decimal for output? - c#

Using C#, I want to format a decimal to only display two decimal places and then I will take that decimal and subtract it to another decimal. I would like to be able to do this without having to turn it into a string first to format and then convert it back to a decimal. I'm sorry I forget to specify this but I don't want to round, I just want to chop off the last decimal point. Is there a way to do this?

If you don't want to round the decimal, you can use Decimal.Truncate. Unfortunately, it can only truncate ALL of the decimals. To solve this, you could multiply by 100, truncate and divide by 100, like this:
decimal d = ...;
d = Decimal.Truncate(d * 100) / 100;
And you could create an extension method if you are doing it enough times
public static class DecimalExtensions
{
public static decimal TruncateDecimal(this decimal #this, int places)
{
int multipler = (int)Math.Pow(10, places);
return Decimal.Truncate(#this * multipler) / multipler;
}
}

You can use: Math.Round(number,2); to round a number to two decimal places.
See this specific overload of Math.Round for examples.

Math.Round Method (Decimal, Int32)

You don't want to format it then, but to round it. Try the Math.Round function.

Take a look at Math.Round

Related

Is there a C# function or overload to Math.Round that will allow abnormal rounding practices?

I have the need to round a number for pricing sort of strangely as follows:
the value of an incoming price will be 3 decimal places (ie. 10.333)
It is necessary to round the first decimal place up if any number past said first decimal place is greater than 0.
for example:
10.300 = 10.3,
10.301 = 10.4,
10.333 = 10.4
before I go creating a custom method to do this I was wondering if anyone was aware of an existing usage/overload of Math.Round() or other already existing package to get this desired result?
Math.Round has an overload that accepts a MidpointRounding enum value, which lets you specify the strategy for rounding.
In your case, you always want to round up, which is called ToPositiveInfinity.
Math.Round(yourValue, 1, System.MidpointRounding.ToPositiveInfinity)
Approach with Math.Ceiling()
decimal input = 10.300m;
decimal result = Math.Ceiling(input * 10m) / 10m;
https://dotnetfiddle.net/Vck4Oa
double d = 10.300;
var result= Math.Ceiling((decimal)d * 10) / 10;

Rounding Off a double value using Math.Round

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.

Truncate Timespan after two decimal places

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

Round to a certain decimal place

I am calculating the average of some values. Everything works fine.
What I want to do is to round the double to the 2nd decimal place.
e.g.
I would have 0.833333333333333333 displayed as
0.83
Is there anyway to do this?
Round the double itself like:
Math.Round(0.83333, 2, MidpointRounding.AwayFromZero);
(You should define MidpointRounding.AwayAwayFromZero to get the correct results. Default this function uses bankers rounding. read more about bankers rounding: http://www.xbeat.net/vbspeed/i_BankersRounding.htm so you can see why this won't give you the right results)
Or just the display value for two decimals:
myDouble.ToString("F");
Or for any decimals determined by the number of #
myDouble.ToString("#.##")
You say displays as - so that would be:
var d = value.ToString("f2");
See Standard numeric format strings
If you actually want to adjust the value down to 2dp then you can do what #middelpat has suggested.
Use
Math.Round(decimal d,int decimals);
as
Math.Round(0.833333333,2);
This will give you the result 0.83.
double d = 0.833333333333333333;
Math.Round(d, 2).ToString();
Try
decimalVar = 0.833333333333333333;
decimalVar.ToString ("#.##");
If you want to see 0.85781.. as 0.85, the easiest way is to multiply by 100, cast to int and divide by 100.
int val = (int)(0.833333333333333333 * 100);
var result = val /100;
It should produce the result you're looking for.

How to get floats value without including exponential notation

In C#, is it possible to perform ToString on a float and get the value without using exponentials?
For example, consider the following:
float dummy;
dummy = 0.000006F;
Console.WriteLine(dummy.ToString());
This gives the output
6E-06
However, what I was is
0.000006
The closest I could find was using the "F" qualifier, however I then need to specify the number of decimal places otherwise the value get rounded.
Is there actually a way of doing this automatically or do I need to do a load of funky logic to either trim zeroes or figure out the number of required decimals.
Thanks;
Richard Moss
Try this
Console.WriteLine(dummy.ToString("F"));
You can also specify number of decimal places. For example F5, F3, etc.
Also, you can check custom format specifier
Console.WriteLine(dummy.ToString("0.#########"));
string dum = string.Format("{0:f99}",dummy).TrimEnd('0');
if (dum.EndsWith(",")) dum = dum.Remove(dum.Length - 1);
Without some further background info, it's hard to tell - but it sounds like you want decimal semantics. So why not use the decimal type instead?
decimal dummy;
dummy = 0.000006M;
The decimal type is more accurate at representing decimal numbers than float or double, but it is not as performant. See here for more info.
Console.WriteLine(dummy.ToString("N5"));
where 5 its number of decimal places
float dummy = 0.000006F;
Console.WriteLine(dummy.ToString("0." + new string('#', 60)));
If you'll be doing this a lot then it makes sense to store the format string in a static field/property somewhere and re-use it, rather than constructing a new string every time:
private static readonly string _allFloatDigits = "0." + new string('#', 60);
// ...
float dummy = 0.000006F;
Console.WriteLine(dummy.ToString(_allFloatDigits));

Categories