0

I dont want to round I want to take 4 places after decimal.

Example:

double something = 0.00038; 

I want the result to be

0.0003   // 8 is discarded 

how can I achieve that?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
john doe
  • 9,220
  • 23
  • 91
  • 167

2 Answers2

5
double result = Math.Truncate(10000 * something) / 10000;
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Karl Anderson
  • 34,606
  • 12
  • 65
  • 80
  • 1
    @MikePrecup's comment on the answer using `float` applies here as well... better to use Decimal – PinnyM Aug 28 '13 at 14:29
1

Just multiply, truncate, then divide.

decimal f = 100.0123456;
f = Math.Truncate(f * 10000) / 10000;

Here is a nice little function you can use

public static decimal MyTruncate(decimal input, int digit) {
    return Math.Truncate(input * Math.Pow(10, -digit)) / Math.Pow(10, -digit);
}

this function truncates anything to the right of the specified digit

where 0 is the ones place, 1 is the tens place and -1 is the tenths place

Logan Murphy
  • 6,120
  • 3
  • 24
  • 42