0

How can i convert decimal to string without rounding and with specific format?

It is my value;

var price = 4569.996M;

I want to this result result = "4.569,99" . I can check to culture for seperators like this

customCulture.NumberFormat.NumberDecimalSeparator = ",";
customCulture.NumberFormat.NumberGroupSeparator = ".";

I try some codes

var result = price.ToString("#,##0.##", CustomCulture);
//when you try this result = "4.570"

var result = Convert.ToDecimal(price).ToString("#,#.#########", customCulture);
//when you try this result = "4.569,996"

var result = price.ToString("N");
//when you try this result = "4,570.00"

 var result = price.ToString("N", customCulture);
 //when you try this result = "4.569,996"

My value can be any value. I just want to seperate with specific format and seperate two digit after comma and not rounding when convert to string.

mth12
  • 13
  • 4
  • "4.569,99" *is* rounding - it's rounding down rather than using Banker's Rounding or rounding away from zero, but it's still rounding. If that's what you mean, please be specific about it. – Jon Skeet Jun 16 '22 at 12:07
  • (You might want to multiply by 100, call `Truncate`, then divide by 100 again, then format... but I can't really tell while the question is unclear.) – Jon Skeet Jun 16 '22 at 12:09
  • @gunr2171 thank you! It is fix my problem. `var result = (Math.Truncate(price * 100) / 100).ToString("N2",customCulture.NumberFormat);` @JonSkeet thank you too, i'll try to make my questions more specific. – mth12 Jun 16 '22 at 12:19

1 Answers1

1

Having unwanted digits after the decimal point you have to round the value, the question is how to round it. In your case it seems that you want to truncate (4569.996 -> 4569.99), i.e. round to zero:

  var price = 4569.996M;

  string result = $"{Math.Round(price, 2, MidpointRounding.ToZero)}";

Or

  string result = Math.Round(price, 2, MidpointRounding.ToZero).ToString();
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215