Limiting double to 3 decimal places

2019-01-05 02:01发布

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.)

Eg.: 12.878999 -> 12.878

If a double has less than 3 decimals, leave unchanged

Eg.:   125   -> 125
       89.24 -> 89.24

I came across this command:

double example = 12.34567;
double output = Math.Round(example, 3);

But I do not want to round. According to the command posted above, 12.34567 -> 12.346

I want to truncate the value so that it becomes: 12.345

8条回答
闹够了就滚
2楼-- · 2019-01-05 02:29

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"));
查看更多
我想做一个坏孩纸
3楼-- · 2019-01-05 02:30
double example = 3.1416789645;
double output = Convert.ToDouble(example.ToString("N3"));
查看更多
劳资没心,怎么记你
4楼-- · 2019-01-05 02:31

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;
}
查看更多
啃猪蹄的小仙女
5楼-- · 2019-01-05 02:32

Multiply by 1000 then use Truncate then divide by 1000.

查看更多
Animai°情兽
6楼-- · 2019-01-05 02:34

In C lang:

double truncKeepDecimalPlaces(double value, int numDecimals)
{
    int x = pow(10, numDecimals);
    return (double)trunc(value * x) / x;
}
查看更多
▲ chillily
7楼-- · 2019-01-05 02:38

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).

查看更多
登录 后发表回答