user3064724
user3064724

Reputation: 125

Check number of decimal places in numeric string

Here is a string.

String num = "10.65"

If the user enters 10.653 then it should tell the user that this takes only up to two decimal places. How can I check this?

Upvotes: 0

Views: 1391

Answers (2)

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

You can check, if the parsed value rounded up to 2 decimal places changes:

var input = "10.625";

double value;
if(!double.TryParse(input, out value) || Math.Round(value, 2) != value)
{
    Console.WriteLine("Wrong input");
}

Upvotes: 3

danish
danish

Reputation: 5600

Since you mentioned "user enters", I guess this is a field on screen. If yes, why not use a numeric input control? Is this web or windows form?

Upvotes: 0

Related Questions