Phoenix_uy
Phoenix_uy

Reputation: 3294

Show only decimals if the number contains one digit after comma in C#?

I have a view in my MVC Razor website and it shows a partial view with the price of a product. Now my problem is that i'm showing the price with this partial view:

@model decimal
<span>@GlobalModelExtensions.Currency.Symbol</span>
<span>@Model.ToString("N0")</span>

This shows a correct price but now my client want that if the price only contains one digit, then he needs to show two decimal places and if the price exceeds one digit then the two decimal places will not be shown.

What's the best approach to achieve that?

UPDATE:
This is an example of what i want:
If the price is 90.659 then it must be shown: 91
If the price is 5.659 then it must be shown: 5.66

Upvotes: 0

Views: 1377

Answers (3)

Inspector Squirrel
Inspector Squirrel

Reputation: 2548

@Model.ToString("#.##");

or

@Model.ToString("N2");

UPDATE: This is an example of what i want: If the price is 90.659 then it must be: 91 If the price is 5.659 then it must be: 5.66

if (@Model < 10) @Model.ToString("#.##") else Convert.ToInt32(@Model).ToString()

Console based demonstration here

Upvotes: 1

D Stanley
D Stanley

Reputation: 152566

You can't put conditional logic in custom number format strings. The best place put that logic in the model and expose the property as a string rather than a floating-point type.

public class MyModel
{
    public decimal Price {get; set;}
    public string FormattedPrice 
    { get 
        {  return Price >= 10 
                ? Price.ToString("#,#")
                : Price.ToString("#,#.00");
        }
    }
}  

Upvotes: 3

greenhoorn
greenhoorn

Reputation: 1561

Something like this?

@if(Model > 9){
   <text>@Model.ToString("N0")</text>
}
else
{
   <text>@Model.ToString("N2")</text>
}

Upvotes: 2

Related Questions