I am writing a piece of code in c# that mimics the behaviour of following SQL function STR in the following case:
declare @number numeric(19,15) = 219.37345462345234235
SELECT str(@number,9,9) -- 219.37345
declare @number numeric(19,15) = 19.37345462345234235
SELECT str(@number,9,9) -- 19.373455
Following is an input output table for this scenario:
I have implemented the following function in C# which accepts a double variable and returns a string which is equal to the result returned by the SQL function STR(@number,9,9)
.
public static string GetCustomStringQuantity(double quantity)
{
string customQuantity ;
int length = (int) Math.Log10(Math.Abs(quantity))+1;
if (length>9)
return "*********";
quantity = Math.Round(quantity, 8 - length,MidpointRounding.AwayFromZero);
customQuantity = quantity.ToString();
customQuantity= (quantity %1==0)?(customQuantity+".").PadRight(9, '0'):customQuantity.PadRight(9, '0');
if (customQuantity.Length > 9)
customQuantity = customQuantity.Substring(0, 9);
else if (customQuantity.Length == 9 && customQuantity.EndsWith("."))
customQuantity = customQuantity.Substring(0, 8);
return customQuantity;
}
How can I make this function better? Or is there a better way to implement this functionality?