当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - More efficient way to prevent a numeric string value from reducing its decimal precision

问题描述:

I have a a program that outputs a list of string values that it receives from a 3rd party application.

A request has been made that end users would like to see all the level of decimal precision to remain at the highest level it is set at. As each new value overwrites the last value there is no need to apply this backward, just forwards.

So if it goes to 3 levels of precision it should remain at that level afterwards.

Eg. if the values received were: 1, 15, 15.2, 4.25, 1.111, 3.4, 1 then the output would be:

1, 15, 15.2, 4.25, 1.111, 3.400, 1.000

I've written the following code which will do the job, but it doesn't seem very elegant to me. Performance is also very important here, as there could be 100s of samples coming up so this shouldn't effect performance. In fact if it's determined that this causes a noticeable slowdown of the application the the requirement will probably be dropped.

 int numberOfDecimals = 0;

private string FormatValueToMinimumNumberOfDecimals(string value)

{

decimal doubleValue;

if (decimal.TryParse(value, out doubleValue))

{

int numberOfDecimals = this.CountDecimalPlace(doubleValue);

if (this.numberOfDecimals > numberOfDecimals)

{

value = doubleValue.ToString(String.Format("N{0}", this.numberOfDecimals.ToString()));

}

else

{

this.numberOfDecimals = numberOfDecimals;

}

}

return value;

}

private int CountDecimalPlace(decimal val)

{

int decimalCount = 0;

decimal ten = 10;

while (val != Math.Floor(val))

{

val *= ten;

decimalCount++;

}

return decimalCount;

}

So the question is can anyone think of a better/faster way of doing this?

Also if there are any obvious issues with the working solution provide, fell free to point them out.

网友答案:

To get the number of decimal places from a string use IndexOf:

var sep = NumberFormatInfo.CurrentInfo.CurrencyDecimalSeparator; 
var pos = val.IndexOf(sep); 
var pre = (pos == -1) ? 0 : val.Length - pos - 1; 

To get the precision from a decimal type use Decimal.GetBits:

var pre = (Decimal.GetBits(val)[3] >> 16) & 0x000000FF; 

Also, you can use NumberFormatInfo instead of String.Format().

NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberDecimalDigits = this.numberOfDecimals;
value = doubleValue.ToString("N", nfi);      
分享给朋友:
您可能感兴趣的文章:
随机阅读: