When ever one passes string with suffix parsing to decimal fails.
decimal testValue;
decimal.TryParse("5M", NumberStyles.Number, CultureInfo.CurrentCulture, out testValue)
Following parse will return false.
Why does TryParse fail when you pass in a string with a suffix?
Because Decimal.TryParse does not support it.
Depending on the value of style, the s parameter may include the following elements:
[ws][$][sign][digits,]digits[.fractional-digits][e[sign]digits][ws]
Elements in square brackets ([ and ]) are optional. The following table describes each element.
ws: Optional white space. White space can appear at the beginning of s if style includes the NumberStyles.AllowLeadingWhite flag. It can appear at the end of s if style includes the NumberStyles.AllowTrailingWhite flag.
$: A culture-specific currency symbol. Its position in the string is defined by the NumberFormatInfo.CurrencyNegativePattern or NumberFormatInfo.CurrencyPositivePattern properties of the NumberFormatInfo object returned by the IFormatProvider.GetFormat method of the provider parameter. The currency symbol can appear in s if style includes the NumberStyles.AllowCurrencySymbol flag.
sign: An optional sign.
digits: A sequence of digits ranging from 0 to 9.
.: A culture-specific decimal point symbol.
fractional-digits: A sequence of digits ranging from 0 to 9.
Because there is no way to parse your string without removing M part. And none of NumberStyles have such a functionality.
I can suggest to Replace your M with empty string but that would be only solve for your case, it won't be a general solution.
decimal testValue;
decimal.TryParse("5M".Replace("M", ""), NumberStyles.Number,
CultureInfo.CurrentCulture, out testValue);
A real-type-suffix specifies number types. It teaches to C# compiler what a numeric literal type considered as. In a string, it means nothing. It is just an another character.
Related
I saw Regex today for the first time. I need a regex formatter for my WPF Textbox like this:
12345,1234
I need a decimal separator like "," or "." and negative Numbers should be allowed.
So you can write something like this:
230,56 / 1289,4 / -1.9 / 63478,1252 / 0.3265
This should not be possible:
086,344 / 34,7000 / 1.0×10−4
A 0 at first if there is not a comma behind there should not be allowed. And if the last Number after the Comma is a 0 is also bad. No scientific notation.
I found a code for simple integer values:
private void Int_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
{
// Just Ints
Regex regex = new Regex("[^0-9]+");
e.Handled = regex.IsMatch(e.Text);
}
So how does a formatter for floating point numbers like my description looks like?
Looking at your requirements, it seems that the following pattern would work:
^-?(?!.*0$)(?!0\d)\d+(?:[,.]\d+)?$
See the demo
^ - Start string ancor.
-? - Optional hyphen to allow for negative values.
(?!.*0) - Negative lookahead to prevent a string that ends with 0.
(?!0\d) - Negative lookahead to prevent a string that starts with 0 and a digit.
\d+ - Any digit at least once.
(?: - Open non-capture group.
[,.] - A comma or dot as decimal delimiter.
\d+ - One or more digits.
)? - Close non-capture group and make it optional.
$ - End string ancor.
If you want to check if user entered valid decimal number, .NET offers you readable and simple way of validating that. Justs use decimal.TryParse
In the spirit of "use the right tool for the job", you should not use regex for such validation.
Just use it like:
var parseOk = decimal.TryParse(textBlock.Text, out _); // here I used _ as parameter name, as it is not relevant
if(! parseOk)
{
// validation failed
}
In order to control how decimal separators are treated, you can use overload fo metnioned method:
public static bool TryParse (string s, System.Globalization.NumberStyles style,
IFormatProvider provider, out decimal result);
And please look at the docs.
Also, you have to decide how number will be stored (float, decimal or double). Fortunately, each of these types exposes two static methods: Parse and TryParse - I encourage you to read about them.
I interpret your requirements as follows:
The string might have an optional "-" character in front
Before the decimal separator, there should be either a single "0", or any number of digits not starting with a "0".
After the decimal separator, there should be either a single "0", or any number of digits not ending with a "0".
This translates straightforward to the following regex:
#"^-?(0|[1-9]\d*)[,\.](0|\d*[1-9])$"
If numbers without decimal separators are allowed (the question is not clear about this), the part starting from the separator would be optional, i.e.
#"^-?(0|[1-9]\d*)([,\.](0|\d*[1-9]))?$"
i want to format a string. Assume there is:
string unformatedString="004897582515"
string stringFormater="{0:00#-###-###-####}"
After formatting:
string result = String.Format(stringFormater, Int64.Parse(unformatedString));
the result is: 000-044-788-9556
I'd like to know why? Because after parsing unformatedString into Int64 I am getting 4897582515 value as integer, but after formatting it there are always additional zeros(it's based on count of zeros in the beginning of unformatedString).
The simple reason 004897582515 is turning into 000-0xx-xxx-xxx with the format specifier "{0:00#-###-###-####}" is because of the 0's at the beginning
Custom numeric format strings
Format specifiers
0 : Zero placeholder
Replaces the zero with the corresponding digit if one is present; otherwise, zero appears in the result string.
Maybe you want "{0:###-###-###-####}"
Format specifiers
# : Digit placeholder
Replaces the # symbol with the corresponding digit if one is present; otherwise, no digit appears in the result string.
Which in worst case will result in "-xxx-xxx-xxxx"
However, you could hack in a TrimStart('-')
Console.WriteLine(string.Format("{0:###-###-###-####}", 004897582515).TrimStart('-'));
Which will remove any leading dash
Output
489-758-2515
Full Demo Here
Why would this exponent throw a FormatException when converted to a decimal using Decimal.Parse.
String stringValue = "8.83080183680678E-05";
Decimal decimalValue = Decimal.Parse(badValue, NumberStyles.AllowExponent);
When the code executes it throws a FormatException
"Input string was not in a correct format."
The code seems to adhere to the MSDN spec: [ws][$][sign][digits,]digits[.fractional-digits][e[sign]digits][ws]
You need to specify that the number format also allows for decimals.
Decimal.Parse(badValue, NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint);
...which is explained in the documentation for AllowExponent:
Indicates that the numeric string can be in exponential notation. The AllowExponent flag allows the parsed string to contain an exponent that begins with the "E" or "e" character and that is followed by an optional positive or negative sign and an integer. In other words, it successfully parses strings in the form nnnExx, nnnE+xx, and nnnE-xx. It does not allow a decimal separator or sign in the significand or mantissa; to allow these elements in the string to be parsed, use the AllowDecimalPoint and AllowLeadingSign flags, or use a composite style that includes these individual flags.
NumberStyles.Float is probably a better choice in this case.
NumberStyles.AllowExponent doesn't include AllowDecimalPoint. You might've wanted to use NumberStyles.Float, which includes "AllowLeadingWhite, AllowTrailingWhite, AllowLeadingSign, AllowDecimalPoint, and AllowExponent".
I need for this to work in a single format statement and to work for both ints and decimals:
For example:
int myInt=0;
decimal myDecimal=0.0m;
// ... Some other code
string formattedResult1=String.Format("{0}",myInt);
string formattedResult2=String.Format("{0}",myDecimal);
The expected results are:
"" (i.e., string.Empty) if the item to be formatted is zero
and a numeric value (e.g., "123.456" for the decimal version) if it isn't.
I need for this to occur exclusively as a result of the format specification in the format string.
This should do:
string formattedResult1 = string.Format("{0:0.######;-0.######;\"\"}", myInt);
The colon introduces a numeric format string. The numeric format string is divided into 3 parts with semicolons: part 1 is for positive numbers, part 2 for negative numbers, and part 3 for zeros. To define a blank string you need to delimit it with double quotes otherwise it doesn't like it.
See MSDN for the full syntax.
based from the accepted answer above i have done the same thing in microsoft "report builder"
this worked for me (shows 2 decimal places, blank for zero) :
,##0.00;-#,##0.00;""
I would like to represent the number 2.3421 as 2.34 but my current formatting shows it as 02.34
If I had the number 1342.323 I would want to show this as 1,342.32
If I had 0.23 this would be shown as 0.23.
What do I change my format string to achieve this? I have:
"{0:0,0.00}"
Use # where a number is optional instead of 0:
"{0:#,0.00}"
See Custom Numeric Format Strings on MSDN:
"#" | Digit placeholder
Replaces the pound sign with the corresponding digit if one is present; otherwise, no digit appears in the result string.
Try this:
{0:#,##0.00}
1342.323 should then be 1,342.32