【C#】数値の扱い

数字の扱い

 * NET Framework 2.0以降ではDecimal型が使えるが、.NET Framework 1.xでは常にDouble型を使う必要がある。
 * Double型は丸めが起こってしまうので、注意。

四捨五入

関数化

// value:対象値、point:小数点桁数
private Decimal GetRoundOffValue(Decimal value, int point)
{
    return Math.Round(value, point, MidpointRounding.AwayFromZero);
}

サンプル

private void button1_Click(object sender, EventArgs e)
{
    Decimal value = Decimal.Parse(this.textBox1.Text);
    int point = int.Parse(this.textBox2.Text);

    this.label1.Text = this.GetRoundOffValue(value, point).ToString();
}

private Decimal GetRoundOffValue(Decimal value, int point)
{
    return Math.Round(value, point, MidpointRounding.AwayFromZero);
}

切り上げ

 * Math.Ceiling()を利用する。
 * 冒頭通り、Double型は丸めが起こってしまうので、Math.Ceiling()の引数に、Double型を入れると戻り値もDouble型となり、その際、丸めが起こってしまうので注意。

関数化

// value:対象値、point:小数点桁数
private Decimal GetRoundUpValue(Decimal value, int point)
{
    decimal roundUpValue = value;
    int degits = 10 * point; // 桁数

    roundUpValue *= degits; // 小数点の位置を右に桁をずらす
    roundUpValue = Math.Ceiling(roundUpValue); // 切り上げ
    roundUpValue /= degits; // 小数点の位置を左に桁を戻す
    return roundUpValue;
}

サンプル

private void button2_Click(object sender, EventArgs e)
{
    Decimal value = Decimal.Parse(this.textBox1.Text);
    int point = int.Parse(this.textBox2.Text);

    this.label1.Text = this.GetRoundUpValue(value, 2).ToString();
}

private Decimal GetRoundUpValue(Decimal value, int point)
{
    decimal roundUpValue = value;
    int degits = 10 * point; // 桁数

    roundUpValue *= degits; // 小数点の位置を右に桁をずらす
    roundUpValue = Math.Ceiling(roundUpValue); // 切り上げ
    roundUpValue /= degits; // 小数点の位置を左に桁を戻す
    return roundUpValue;
}

切り捨て

 * Math.Floor()を利用する。
 * 冒頭通り、Double型は丸めが起こってしまうので、Math.Floor()の引数に、Double型を入れると戻り値もDouble型となり、その際、丸めが起こってしまうので注意。

関数化

// value:対象値、point:小数点桁数
private Decimal GetRoundDownValue(Decimal value, int point)
{
    decimal roundDownValue = value;
    int degits = 10 * point; // 桁数

    roundDownValue *= degits; // 小数点の位置を右に桁をずらす
    roundDownValue = Math.Floor(roundDownValue); // 切り捨て
    roundDownValue /= degits; // 小数点の位置を左に桁を戻す
    return roundDownValue;
}

サンプル

private void button3_Click(object sender, EventArgs e)
{
    Decimal value = Decimal.Parse(this.textBox1.Text);
    int point = int.Parse(this.textBox2.Text);

    this.label1.Text = this.GetRoundDownValue(value, 2).ToString();
}

private Decimal GetRoundDownValue(Decimal value, int point)
{
    decimal roundDownValue = value;
    int degits = 10 * point; // 桁数

    roundDownValue *= degits; // 小数点の位置を右に桁をずらす
    roundDownValue = Math.Floor(roundDownValue); // 切り捨て
    roundDownValue /= degits; // 小数点の位置を左に桁を戻す
    return roundDownValue;
}

参考資料

http://www.atmarkit.co.jp/fdotnet/dotnettips/703mathfloorceiling/mathfloorceiling.html