简体   繁体   中英

Add two decimals when the number has even if it has just one decimal (C#)

I want to add two decimals to those numbers who has at least just one decimal. I'm using C# and now I have this instruction but it only returns one decimal position:

string.Format("{0:#,##0.#}", number)

What do I need to put in that instruction to let show the number with two decimal position if the number has at least one decimal? Point that, if the number does not have any decimal, the number is shown with no decimal numbers. That is correct for what I need.

EDIT answer with examples:

4.156,5 has to be 4.156,50

8.150 has to be 8.150

12.230,22 has to be 12.230,22

EDIT 2: Note that I also want to keep the dot separator for thousand digit. So I want to find a string format formula that can include these variants.

Thank you in advance.

Regards

Option 1:

One idea would be to first format with two decimals:

var str = string.Format("{0:#,##0.00}", number);

After this, if the string ends with "(decimalseparator)00", remove this portion:

str = str.Replace(CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator + "00", "")

Not nice, but it works

Option 2:

First multiply by 100 and round to the next integer:

var rounded = (int)Math.Round(100 * number);

Then check if the integer is divisible by 100 and choose one of two format strings:

string.Format(rounded % 100 == 0 ? "{0:#,##0}" : "{0:#,##0.00}", number);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM