1

I'm working with .net core, and I having some issues formatting one number.

I have a decimal like this

decimal d = 362250;

And i want to show it rounded to 4 digits

3623

I was reading both Decimal.ToString formatting and custom number formatting but i wans't be able to do it

I try :

Console.WriteLine($"{d:####}"); //show 362250
Console.WriteLine($"{d:####,}"); //show 362

How can i achieve that?

I know its so simple, but I fighting with it for 2 hours!

Juan Salvador Portugal
  • 1,233
  • 4
  • 20
  • 38
  • 5
    That's not rounded, though, that's a fundamentally different number -- which is why mere formatting won't do it and you'll have to apply some calculation, though it's not clear what. What should `108` become? How about `123456789`? – Jeroen Mostert Feb 18 '20 at 13:50
  • @Juan - what about Math.Ceiling(d / 100) ? – yob Feb 18 '20 at 14:12
  • @JeroenMostert Hi, ty! `108` should become `108`, and `123456789` `1233` – Juan Salvador Portugal Feb 18 '20 at 14:23
  • That's a really weird way of treating the numbers since you erase the magnitude. Even then, shouldn't `123456789` become either `1235` (rounding `1234.5`)? Otherwise it's not clear why `362250` would become `3623`. – Jeroen Mostert Feb 18 '20 at 14:35
  • @JeroenMostert You're right, it should be `1235` i miss up, i want to show the numbers like exel do when you show less digits in the cell, do you know what i mean? – Juan Salvador Portugal Feb 18 '20 at 14:38
  • 1
    Not really, no -- my Excel refuses to eliminate significant digits. `123456789` will never shrink, no matter how few digits I ask for. At most it will reduce the number to `1.235E+08` in scientific notation, which maintains the magnitude (that would be `#.###E+00` as a C# format string, which reduces `108` to `1.08E+02`). – Jeroen Mostert Feb 18 '20 at 14:40
  • 1
    No idea why are you trying this, but `var d=362250; var sig=4; return Math.Round(d/Math.Pow(10,(Math.Ceiling(Math.Log10(Math.Abs(d)))-sig)))` d=number, sig=significant portion – Mike Makarov Feb 18 '20 at 15:04
  • @MikeMakarov: be careful in that all those calculations happen on `double`s; `Math` does not have separate support for `decimal`. This matters because, in principle, decimal rounding on `decimal`s is always possible to do precisely, unlike for `double`s, so the outcomes can differ. – Jeroen Mostert Feb 18 '20 at 15:11
  • @JeroenMostert he's cutting a value UP to x digits :) I do understand your concern, and agree in theory there can be a value that would trigger that Double epsilon noise, but for hist scenario, I'd say, i't ultimately not going to make things worse... – Mike Makarov Feb 18 '20 at 15:31

0 Answers0