2

I have read many examples of rounding numbers but nothing that solves my problem...

I may be missing something obvious but I tried:

string.Format("{0:0.0}", 1.998) = "2.0"
(1.998).ToString("0.0") = "2.0"
(1.998).ToString("0.#") = "2"
Math.Round(1.998, 1) = 2

I need: 1.9

Note: value 1.998 could be 1.998xxx

Seemed pretty simple but can't get this result...

  • Why should 1.998 be rounded to 1.9? Do you want to round down to one decimal? – andreas Oct 25 '18 at 20:33
  • 2
    Possible duplicate of [Rounding down to 2 decimal places in c#](https://stackoverflow.com/questions/13522095/rounding-down-to-2-decimal-places-in-c-sharp) – grek40 Oct 25 '18 at 20:34
  • I know the duplicate is not perfect, but you should be able to transform the solution from 2 to 1 decimal places ;) – grek40 Oct 25 '18 at 20:34
  • What result do you expect for -1.998 as the input? – mjwills Oct 25 '18 at 20:38

1 Answers1

4

You want to truncate from what I understand. Try this:

(Math.Truncate(1.998m * 10))/10

Forcing decimal instead of double prevents problems with floating point calculations. Also, check this post which explains rounding differences between Truncate, Round, Floor and Ceiling to find out which one suits your needs best.

mjwills
  • 23,389
  • 6
  • 40
  • 63
Felipe Martins
  • 184
  • 2
  • 12
  • Thanks ! This seems to give me the result I need. But I raises another question, using doubles for my variables, I get this strange result: `code`0.6 + 0.3 = 0.89999999999999991`code` – Michel Poirier Oct 26 '18 at 13:44
  • 1
    About this strange result: 0.6 + 0.3 = 0.89999999999999991 Forcing to decimal like you sugested in your answer, did the trick ! Thanks twice ! – Michel Poirier Oct 26 '18 at 13:52