Limiting double to 3 decimal places

前端 未结 8 2150
小鲜肉
小鲜肉 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 05:02

    Doubles don't have decimal places - they're not based on decimal digits to start with. You could get "the closest double to the current value when truncated to three decimal digits", but it still wouldn't be exactly the same. You'd be better off using decimal.

    Having said that, if it's only the way that rounding happens that's a problem, you can use Math.Truncate(value * 1000) / 1000; which may do what you want. (You don't want rounding at all, by the sounds of it.) It's still potentially "dodgy" though, as the result still won't really just have three decimal places. If you did the same thing with a decimal value, however, it would work:

    decimal m = 12.878999m;
    m = Math.Truncate(m * 1000m) / 1000m;
    Console.WriteLine(m); // 12.878
    

    EDIT: As LBushkin pointed out, you should be clear between truncating for display purposes (which can usually be done in a format specifier) and truncating for further calculations (in which case the above should work).

    0 讨论(0)
  • 2020-11-27 05:07

    I can't think of a reason to explicitly lose precision outside of display purposes. In that case, simply use string formatting.

    double example = 12.34567;
    
    Console.Out.WriteLine(example.ToString("#.000"));
    
    0 讨论(0)
提交回复
热议问题