How to truncate a double variable to 4 decimals in c #? [closed]

0

How to make a double variable show me only 4 digits after the decimal? that is not round.

    
asked by Luis García 14.09.2017 в 05:42
source

2 answers

2

I would do so, easy if the decimal precision is not mandatory:

   double example = 12.345678;
   var result = example.ToString("#.0000");
   double numRounded = Convert.ToDouble(result); // No es totalmente preciso

If you need decimal precision you should use decimal variable numbers instead of double.

 decimal numToRound = 12.345678m;
 decimal numResult = Math.Truncate(numToRound * 10000m) / 10000m;
 // Valor en numResult 12.3456
    
answered by 14.09.2017 в 06:18
1

The Math.Floor(numero) function allows you to get the whole value of a number without rounding it up.

You could then multiply your number by 10000 , get the whole value with Math.Floor and finally divide by 10000 to return to the original value but keeping only the 4 decimal places.

Example:

double numero = 123.456789;
double numeroConFormato = Math.Floor(numero * 10000) / 10000; // -> 123.4567
    
answered by 14.09.2017 в 07:39