Make round a decimal value
- Hello. I am developing a financial program. I use decimal as a main data type in my application. Sometimes, I need to make round a decimal value. Please tell me some functions to solve my problem. Example:
d = 12345678.376
Create a Round1 function so that:
Round1(d, 2) = 12345678.38
Round1(d, -4) = 12350000
Create a Round2 function so that
Round2(d, 2) = 12345678.37
Round2(d, -4) = 12340000
I tried some functions from Math class but failed. Please help me. Thanks.
Answers
- Hi,
Hope these are what you are looking for.
public static decimal Round(decimal d,int decimals) { if (decimals < 0) { decimal pow=Convert.ToDecimal(Math.Pow(10, -decimals)); return Convert.ToInt32((d / pow))*pow; } else { return Math.Round(d, decimals); } } public static decimal Round2(decimal d, int decimals) { if (decimals < 0) { decimal pow = Convert.ToDecimal(Math.Pow(10, -decimals)); return Math.Floor((d / pow)) * pow; } else { decimal pow = Convert.ToDecimal(Math.Pow(10, decimals)); d = d * pow; return Math.Floor(d)/pow; } }- Marked As Answer byLe Vo Quang Friday, November 06, 2009 11:15 AM
All Replies
- Hi,
have a look at this link
http://msdn.microsoft.com/en-us/library/7x5bacwt(VS.80).aspx
Best Regards, C.Gnanadurai ----------------------- Please mark the post as answer if it is helpfull to you Hi,
have a look at this link
http://msdn.microsoft.com/en-us/library/7x5bacwt(VS.80).aspx
Best Regards, C.Gnanadurai ----------------------- Please mark the post as answer if it is helpfull to you
It don't help me anything. It only a custom string format for a numeric value. Please understand my question: I want to make round a numeric value, not formatting output string. Thanks.- Hi,
Hope these are what you are looking for.
public static decimal Round(decimal d,int decimals) { if (decimals < 0) { decimal pow=Convert.ToDecimal(Math.Pow(10, -decimals)); return Convert.ToInt32((d / pow))*pow; } else { return Math.Round(d, decimals); } } public static decimal Round2(decimal d, int decimals) { if (decimals < 0) { decimal pow = Convert.ToDecimal(Math.Pow(10, -decimals)); return Math.Floor((d / pow)) * pow; } else { decimal pow = Convert.ToDecimal(Math.Pow(10, decimals)); d = d * pow; return Math.Floor(d)/pow; } }- Marked As Answer byLe Vo Quang Friday, November 06, 2009 11:15 AM
- I checked Round1 , it isn't right. This is my fix:
public static decimal RoundUp(decimal value, int decimals) { if (decimals < 0) { decimal pow = Convert.ToDecimal(Math.Pow(10, -decimals)); decimal d1 = value / pow; decimal d2 = Math.Truncate(d1); if (d1 != d2) { d2 = d2 + 1; } return d2 * pow; } else { decimal pow = Convert.ToDecimal(Math.Pow(10, decimals)); decimal d1 = value* pow; decimal d2 = Math.Truncate(d1); if(d1 != d2) { d2 = d2 + 1; } return d2 / pow; } }
Thanks.


