Check string is decimal with 2 decimal places - c#

I have a textbox that a user enters a number into. I need to ensure that the number is at most 5 numbers before the decimal place and mandatory 2 digits after. The number must always have 2 digits after the decimal point. What Regex could I use to check this? (The solution is in C#)

Something like this:
String source = ...;
if (Regex.IsMatch(source, #"^[0-9]{,5}\.[0-9]{2}$")) {
//TODO: put relevant code here
}
If you want at least one digit before decimal point, the pattern will be
#"^[0-9]{1,5}\.[0-9]{2}$"

Just Try this code
string Value= "12345.63";
if (Regex.IsMatch(Value, #"^[0-9]{5}\.[0-9]{2}$"))
{
Console.WriteLine(Value);
}
else
{
Console.WriteLine("Not Match");
}
Console.ReadKey();

Related

String Format Returns Unexpected Results

I have a simple class that contains a property Format which is set to any given format specifier. I then use the property of this class to, as the name suggest, format the string.
Take the following example:
public class FormatDefinition {
public string Format { get; set; }
}
class Program {
static void Main() {
var formatDefinition = new FormatDefinition {
Format = "N"
};
var number = 20.5;
var formatOne = string.Format("{0:" + formatDefinition.Format + "}", number);
var formatTwo = string.Format("{0:formatDefinition.Format}", number);
var formatThree = $"{number:formatDefinition.Format}";
Console.WriteLine(formatOne); // 20.5
Console.WriteLine(formatTwo); // formatDefinition21Format
Console.WriteLine(formatThree); // formatDefinition21Format
Console.ReadLine();
}
}
Can someone please explain why formatTwo and formatThree have a result of formatDefinition21Format? It seems the period . is replaced by the formatted number.
You are specifying a custom numeric format string consisting of the string "formatDefinition.Format".
This is taken to mean constant string "formatDefinition" followed by the decimal point (and therefore the entire number goes here) followed by constant string "Format".
The number is rounded to zero decimal places because there are no digits specified after the decimal point.
The string formatDefinition.Format is not interpreted as C# code.
According to the documentation for Custom Number Format Strings:
For fixed-point format strings (that is, format strings that do not
contain scientific notation format characters), numbers are rounded to
as many decimal places as there are digit placeholders to the right of
the decimal point.
It's because you have a decimal point with no digit placeholders to its right. You're telling it to round the number to zero decimal places - in other words, round to the nearest whole number.
These are all functionally the same - all return a22b.
string.Format("{0:a.b}", 21.5);
string.Format("{0:a0b}", 21.5);
string.Format("{0:a0.b}", 21.5);
Here's a DotNetFiddle.

Math.Floor to x digits after decimal

I need to display two digits after decimal point while rounding to floor as a percentage. I wrote out this code to do so, but this looks too complex, is there another more effecient way of doing this?
double decimalPlacesFactor =Math.Pow(10, numberOfDigits+2);
percentage = Math.Floor((NumA/NumB)*decimalPlacesFactor)/decimalPlacesFactor *100;
The output should look like
99.78 %
Use the ToString() methode to convert your number to a string. Display it as a floating point with X digits by using the argument "FX". e.g. "F2" for two digits
string percentage = Math.Floor(NumA/NumB).ToString("F"+numberOfDigits);
Depends on how you want to display the percentage value, but I am guessing you'll want to show string of the percentage? What about:
string percentage = Math.Floor(NumA/NumB).ToString("0.00");
Console.WriteLine(Math.Floor(2.3).ToString("0.00")); //this will output 2.00
If you want to make the number of digits after decimal configurable you could create the masking string beforehand, with something like this:
private string CreateMaskingString(int numberOfDigits)
{
var sb = new StringBuilder("0.");
sb.Append(new string('0', numberOfDigits));
return sb.ToString();
}
And usage would look like this:
Console.WriteLine(Math.Floor(2.3).ToString(CreateMaskingString(2))); //this will output 2.00
A much more simple and elegant solution looks like this, as has been pointed out by RomCoo:
string percentage = Math.Floor(NumA/NumB).ToString("F" + numberOfDigits);
What does the "F" mean here? You can read the explanation here. But basically:
The fixed-point ("F") format specifier converts a number to a string of
the form "-ddd.ddd…" where each "d" indicates a digit (0-9). The
string starts with a minus sign if the number is negative.

forcing four decimal places for double

I need to display particular value to 4 decimal places for sure.
Here is the code
row["Money"] = StringMgt.ToGlobalizationString("N4", dblMoney);
public static string ToGlobalizationString(string format, double dblNumber)
{
return dblNumber.ToString(format, CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name));
}
Which outputs
1.4305228 to 1.4305 (which is fine!)
0.30704454 to 0.307 (I need to display 4 decimal places consistently)
How do I force it to display four decimal places (ex 0.3070)? I have seen similar posts but did not understand properly.
Thanks.
So the way I understand it you need exactly four decimals, otherwise pad with 0 to the right. So it should be .ToString("0.0000").
I'd use the F-Format specifier:
void Main()
{
double input = 3.213112134;
string result = input.ToGlobalizationString("F4").Dump();
}
public static class Extensions
{
public static string ToGlobalizationString(this double input, string format)
{
return input.ToString(format, CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name));
}
}
This will return a string with 4 decimal points. Change it to your liking.
Use following format:
row["Money"] = StringMgt.ToGlobalizationString("0.0000", dblMoney);
I have tried all the suggestions. If the output value has zero as the 4th decimal its not displaying it. for ex, instead of 0.3070 it is displaying 0.307. If thh fourth decimal is other than zero, it works just fine.
example:
Input value: 0.511519926
Output: 0.5115
Input Value: 0.45895644
Output Value: 0.459
I took off cultural settings and still it didn't work.
I did this and it worked
ClassA.gridTable.Columns[17].DefaultCellStyle.Format = "#,0.0000";
Thanks all for your valuable inputs.

TryParse for numbers in C#?

So I want to use a TryParse method, but so far I can do it only with integer or double value. However, I want to check if the value is a number, and if it's not (if it is a string for instance) to get a false value. Something like IsDigit() is Java.
static void Main()
{
int number;
Console.Write("Enter a number: ");
bool result = Int32.TryParse(Console.ReadLine(), out number);
if (result)
{
Console.WriteLine("The input number is an integer.");
}
else
{
Console.WriteLine("The input number is not an integer.");
}
}
So I want to do that, but instead of checking for an integer value, I'd like to check for a numerical value. So if anybody can tell me what method I can use I'd be very happy.
Thanks in advance!
use double:
double number;
bool result = double.TryParse(Console.ReadLine(), out number);
This will parse any real number.
TryParse for decimal or double types is your limit for built in methods. If you want more than that, you'd have to parse the string yourself. The can be quite easily done using a regex, such as
^-?[0-9]+\.?[0-9]*([Ee][+-]?[0-9]+)?$
bool result = double.TryParse(mystring, out num);
The double.TryParse also works on integers.
For a single character, there's Char.IsDigit(). In that case you may want to look at Console.ReadKey() instead of reading a whole line. By the way, Char.IsDigit() also matches digits from other cultures.
For multiple characters you'll need to think about what you want to accept. decimals, exponents, negative numbers, or just multiple digit characters?
You could try a regular expression
var regex = new Regex(#"^-*[0-9\.]+$");
var m = regex.Match(text);
if (m.Sucess)
{
Console.WriteLine("The input number is an integer.");
}
else
{
Console.WriteLine("The input number is not an integer.");
}
You can also allow separators by including them in the regex.
static bool enteredNumber()
{
int intValue;
double doubleValue;
Console.Write("Enter a number: ");
string input = Console.ReadLine();
return Int32.TryParse(input, out intValue) ? true : double.TryParse(input, out doubleValue);
}

Sum up Double ReadLine values?

I'm new to C# programming and I'm not sure what I'm doing wrong because I can't sum up numbers that are Double. If I input 2,5 and 2,5 I get 5, but if I enter 2.5 and 2.5 I get zero when I use a dot instead of a comma between the numbers. Why this?
I add some of my code:
private void ReadInputAndSumNumbers()
{
while (!done)
{
Console.Write("Number: ");
if (double.TryParse(Console.ReadLine(), out num))
{
if (num == 0)
{
done = true;
}
else
{
sum += num;
}
}
}
}
My settings are to use a comma, but I would like the user to be able to enter a value with dot also
How are you converting your ReadLine input into Doubles? Most of the conversion operations are locale-specific, so if your Windows settings have , as the decimal separator, this setting is respected.
Example:
string enteredByUser = Console.ReadLine();
// uses user-specific Windows settings (decimal separator might be ",")
double myDouble1 = double.Parse(enteredByUser);
// uses default settings (decimal separator is always ".")
double myDouble2 = double.Parse(enteredByUser, CultureInfo.InvariantCulture);
A short side note: If you parse user input, you should look into double.TryParse, since this is more robust than double.Parse or Convert.ToDouble, since it allows you to detect faulty input without resorting to exception handling.
EDIT: If you want to support both comma and dot, you need to convert dots into commas (or vice versa) first. String.Replace can help you here. Note, though, that this approach will break if the user tries to enter a thousands separator (1.000,00 -> 1.000.00 or 1,000,00 -> error). The recommended way to do it is to
only accept the decimal separator specified in Windows, if the input comes from an end-user (i.e., keep your code as it is) and
only accept the neutral culture (.), if the input comes from some machine-generated output or file.
A sample for caculate the double sum
static void Main(string[] args)
{
var retVal = 0.0;
var sum = 0.0;
while (true)
{
Console.WriteLine("Enter input:");
string line = Console.ReadLine();
if (line == "exit")
{
break;
}
double.TryParse(line, NumberStyles.Any, CultureInfo.InvariantCulture, out retVal);
sum += retVal;
Console.WriteLine(string.Format("Double Value : {0}", sum ));
}
Console.ReadKey();
}

Categories