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
  • 94,086
  • 102
  • 195
  • 339
john doe
  • 8,658
  • 22
  • 77
  • 159

2 Answers2

5
double result = Math.Truncate(10000 * something) / 10000;
Soner Gönül
  • 94,086
  • 102
  • 195
  • 339
Karl Anderson
  • 34,026
  • 12
  • 64
  • 79
  • 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
  • 5,920
  • 3
  • 23
  • 41