Skip to content
February 21, 2013 / windperson

C# 將小數點後指定位數的數值去掉的方法

例如只要保留小數點後四位,0.012345變成0.0123-0.987654變成-0.9876這樣。

用.net Framework提供的Math.Floor(),然後包裝一下寫成可以直接拿來用的函式如下:

double GetFrag(double input, int digit)
{
  if(digit < 0 ) {return Math.Floor(input);}
  double pow = Math.Pow(10, digit);
  double sign = input >= 0 ? 1 : -1;
  return sign * Math.Floor( sign * input *pow) / pow;
}

這樣至少比那種得『NIHS』的天才先把浮點數轉成字串然後再用Regular Expression去parsing抓match group的方式快而且可靠多了。

Advertisements

2 Comments

Leave a Comment
  1. gschen1024 / Mar 19 2013 8:52 PM

    謝謝,不過此程式有些情況會錯誤:
    當 digit = 1,
    input = 4.1 結果為 4
    input = 4.2 結果為 4.1
    input = 3.1 結果為 3
    input = 3.2 結果為 3.1

    其他的好像就沒問題…

    • windperson / Apr 20 2013 9:44 AM

      .net的執行環境版本是?我在.net 4.0上測試是對的。

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: