开发者

how to take 6 numbers after the dot - but without round the number?

how to take 6 开发者_如何学编程numbers after the dot - but without round the number ?

for example:

102.123456789 => 102.123456

9.99887766 => 9.998877

in C# winforms

thak's in advance


You can use the Math.Truncate method and a 10^6 multiplier:

decimal x = 102.12345689m;
decimal m = 1000000m;
decimal y = Math.Truncate(m * x) / m;
Console.WriteLine(y); // Prints 102.123456


System.Math.Truncate (102.123456789 * factor) / factor; 

In your case factor is 10^6; read more


  public decimal TruncateDecimal(decimal decimalToTruncate, uint numberOfDecimalPlacse)
  {
     decimal multiplication_factor = (decimal)Math.Pow(10.0, numberOfDecimalPlacse);
     decimal truncated_value = (long)(multiplication_factor * decimalToTruncate);
     return (truncated_value / multiplication_factor);
  }


I know this is ugly using strings, but thought I'd put it anyway:

double x = 9.9887766;
string[] xs = x.ToString().Split('.');
double result = double.Parse(xs[0] + "." + xs[1].Substring(0, Math.Min(xs[1].Length, 6)));


Might be a long winded way, but how about turning it into a string, locating the decimal point and then grabbing the string minus anything after the 6th decimal place. You could then turn it back into a decimal.


It's crude but how about:

decimal Number = 102.123456789;
string TruncateTarget = Number.ToString();
decimal FinalValue = Decimal.Parse(TruncateTarget.Substring(0, TruncateTarget.IndexOf('.') +6));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜