Arturo Martinez Arturo Martinez - 1 month ago 16
C# Question

Detect if string has decimal

I'm printing in my header a string that have number values, some of them have decimals and some of them do not. What I want to do is to print the value with the decimal if it exists and add a preceding "$"; otherwise, just print the value but taking the decimal part ".00"

This is my code:

var listDay = data.Where(c => c.Fecha >= actualDate && c.Fecha <= actualDateMax).ToList();
var haveDataDay = listDay.Count() > 0;

<h4 class="semi-bold">
@if (haveDataDay)
{ @valueDateDay.ToString("F2") }
else
{ @this.FP("lbl.loader.nodata") }
</h4>


Some of the values I have are:

2112.34
99.00
20.00
456.12


and the output I'm looking for is:

$2,112.34
99
20
$456.12

Answer

You can detect if a decimal is an integer by finding if there is a remainder after dividing by 1:

99 % 1 == 0 // true
456.12 % 1 == 0 // false

So, your final code might look like:

valueDateDay.ToString(valueDateDay % 1 == 0 ? "N0" : "C2");