How to make a double variable show me only 4 digits after the decimal? that is not round.
How to make a double variable show me only 4 digits after the decimal? that is not round.
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
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