C #: rounded decimal place to display only when the decimal point is 0 (for example: 3.00 & # 8594; 3)

I store the amount in decimal (18.2). But most of my data is actually an integer with several decimal places. Therefore, when I show the quantity for each item in the table, the number display is all 3.00, 4.00, 5.00, etc.

I feel it is weird to display all 0 as a decimal point. I want to format the number on display if the decimal point is 0.

I am currently showing a quantity similar to this:

<td id=" amnt@ (item.FoodID)" class="amountfield"> @Html.DisplayFor(modelItem => item.FoodAmount) </td> 

Any idea ?? Appreciate every help ... thanks ...

+4
source share
5 answers

Looking at your code, I assume that you are using ASP.Net MVC for your application. You can use DataAnnotation to format your data.

You can try using DisplayFormat in the model property.

 [DisplayFormat(DataFormatString = "{0:0.##}")] Decimal FoodAmount{ get; set; } 
+14
source

Use ToString(string) with a custom format using the "#" special format specifier

 item.FoodAmount.ToString("0.##") 

This shows up to two digits, but omits them if they are immaterial zeros.

+4
source

Maybe something like this will help ...

 @Html.DisplayFor(modelItem => item.FoodAmount % 1 == 0 ? item.FoodAmount.ToString("F0") : item.FoodAmount.ToString("F2")) 

This should provide the following results:

 FoodAmount | Output -------------------- 3.00 | 3 3.01 | 3.01 3.5 | 3.50 

I deliberately settled this on one line according to your Html Helper code, but you can create a helper function / extension method for it if you prefer.

The main idea is to get the remainder of dividing by 1. If the result is zero (that is, it can be divided by 1 without a remainder), then it can be considered an integer

Alternative : it will also be an opportunity and can improve reading ...

 item.FoodAmount.ToString("F2").TrimEnd('0', '.') 

It may even give you better results ...

 FoodAmount | Output -------------------- 3.00 | 3 3.01 | 3.01 3.5 | 3.5 
+2
source

DataFormatString works fine in ViewModel

It will also add a thousand separators if necessary.

 [DisplayFormat(DataFormatString = "{0:#,##0.##}")] 
0
source

It worked better for me

 [Test] public void DecimalFormatTests() { var amt1 = 1000000m; var amt2 = 1000000.10m; var format = "0.#"; Console.WriteLine(amt1.ToString("\\£0,0.#")); Console.WriteLine(amt2.ToString("\\£0,0.#")); } 

Output:

£ 10.00,000
£ 10,00,000.1

0
source

Source: https://habr.com/ru/post/1386072/


All Articles