how do I set the number of decimals I want to show from a double in c #

0

My problem is that I am using Math.Round and it is rounding, what I need is that it only shows me a single decimal without being rounded

This is my normal result

double rap = 0;
 rap = (11300 - 8508.54)* 0.015);

That this gives me as a result 41.8719

This is when I use Math.Round

 double rap = 0;
     rap = Math.Round(11300 - 8508.54)* 0.015,1);

It gives me as a result 41.9 and what I need is that you give 41.8

This is what I need 41.8 that is my result

    
asked by Marco Eufragio 12.11.2018 в 21:45
source

2 answers

2

The problem is that you are doing a Round, so, 41.8719 rounded to a decimal of 41.9.

To "truncate" the value to a decimal you may want to do this:

double rap = 0;
rap = ((11300 - 8508.54)* 0.015);
rap = Math.Floor(rap * 10) / 10;

I hope it serves you.

Good luck!

    
answered by 12.11.2018 / 22:02
source
2

You can use the Truncate function

Round the decimal / double to the nearest integer close to zero.

If we use Math.Truncate(41.8719) the result would be 41. If you notice, delete the 8719 because the nearest integer is 41.

So, if we want two decimals, we can multiply that value by 100 so that it does not eliminate those decimals when applying the function, and then divide into 100 again to keep the two decimals we wanted.

Like this:

rap = Math.Truncate(41.8719*100)/100;

This will give Math.Truncate(4187.19)/100 = 4187/100 = 41.87

If you want a decimal, multiply and divide by 10, if you want three, by 1000, etc.

    
answered by 13.11.2018 в 00:22