user1790563 user1790563 - 4 months ago 32
C# Question

Difference between Decimal and string Decimal in C#

Example: These Two values will come simultaneously ..


  • if
    Value
    comes as
    0.56
    I have to to multiply it by
    100
    and pass it as
    56

  • if
    Value
    comes as
    56.0
    then I have to divide it by
    100



I tried this with the following code

string s = "56.0" or "0.56"
float dval;
bool bval = float.tryparse(s,out dval);
if (bval)
{
dval = decimal.parse(s); // if dal ="0.56"
dval = dval*100;
}
else
{
dval = decimal.parse(s); // if dal ="56"
dval = dval/100;
}


How can I do this because every time this returns
True
?

Answer

TryParse returns true if it sucessfully parsed a number. So, it's true in both cases. You need to check whether the parsed number is less 1 or bigger (this is my speculation, of course) Try this:

string s = "56.0";
float dval;
bool bval = float.TryParse(s, out dval);
if (bval)
{
    if (dval < 1)
        dval *= 100;
    else
        dval /= 100;
    Console.WriteLine(dval);
}
else
{
    Console.WriteLine("it's not a number");
}