1

I am using Unity Engine to make a game. I am using a double variable and want it to only display the number till two decimal places.

public double nos = 0;

For eg: if nos = 17.2369...; I want it to display nos = 17.23;

P.S.: I don't want to round it off or smt.

How to make that happen?

  • If you want exactly 2 places, you _will_ need to round to some extent. As is, this question has no solution since you exclude the only thing that would make one possible. – Fildor Mar 12 '23 at 10:27
  • This answer looks promising: https://stackoverflow.com/a/54184194/1974021 provided it is for display purposes – DasKrümelmonster Mar 12 '23 at 10:33
  • Does this answer your question? [How to format a float number without rounding?](https://stackoverflow.com/questions/8946168/how-to-format-a-float-number-without-rounding) – shingo Mar 12 '23 at 10:53

1 Answers1

0

You are right, string formatting also does some rounding. This should work then:

double num = 15.345324;
num = Math.Truncate(100 * num) / 100;
// num = 15.34

Use 10 to the power of decimal places (here: 100) you want to have as factor.

100 -> 2dps

1000 -> 3dps

etc.

Edit: In a more general way one could do sth like this

double num = 12.3456789;
double numOfDecimals = 2;
num = Math.Truncate(Math.Pow(10, numOfDecimals) * num) / Math.Pow(10, numOfDecimals);
anjelomerte
  • 286
  • 1
  • 9