Limiting double to 3 decimal places

前端 未结 8 2149
小鲜肉
小鲜肉 2020-11-27 04:38

This i what I am trying to achieve:

If a double has more than 3 decimal places, I want to truncate any decimal places beyond the third. (do not round.)



        
相关标签:
8条回答
  • 2020-11-27 04:44

    You can use:

    double example = 12.34567;
    double output = ( (double) ( (int) (example * 1000.0) ) ) / 1000.0 ;
    
    0 讨论(0)
  • 2020-11-27 04:57
    double example = 3.1416789645;
    double output = Convert.ToDouble(example.ToString("N3"));
    
    0 讨论(0)
  • 2020-11-27 04:58

    Multiply by 1000 then use Truncate then divide by 1000.

    0 讨论(0)
  • 2020-11-27 04:58

    Good answers above- if you're looking for something reusable here is the code. Note that you might want to check the decimal places value, and this may overflow.

    public static decimal TruncateToDecimalPlace(this decimal numberToTruncate, int decimalPlaces)
    {
        decimal power = (decimal)(Math.Pow(10.0, (double)decimalPlaces));
    
        return Math.Truncate((power * numberToTruncate)) / power;
    }
    
    0 讨论(0)
  • 2020-11-27 04:59

    In C lang:

    double truncKeepDecimalPlaces(double value, int numDecimals)
    {
        int x = pow(10, numDecimals);
        return (double)trunc(value * x) / x;
    }
    
    0 讨论(0)
  • 2020-11-27 05:00

    If your purpose in truncating the digits is for display reasons, then you just just use an appropriate formatting when you convert the double to a string.

    Methods like String.Format() and Console.WriteLine() (and others) allow you to limit the number of digits of precision a value is formatted with.

    Attempting to "truncate" floating point numbers is ill advised - floating point numbers don't have a precise decimal representation in many cases. Applying an approach like scaling the number up, truncating it, and then scaling it down could easily change the value to something quite different from what you'd expected for the "truncated" value.

    If you need precise decimal representations of a number you should be using decimal rather than double or float.

    0 讨论(0)
提交回复
热议问题