473,662 Members | 2,724 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Let no good deed go unpunished--why you can't be too careful with C#DecimalParse NumberStyles

Here is a classic example of why C# is like beating your head against
the wall. I can tell you where the error is in the below code--it's
the "NumberStyl es" property of DecimalParse (which extracts a decimal
from a string)--and how to fix it--you leave it out--but why? WHY?
Y?

We'll never know... that's just the way it is. Some things were meant
to be...

(PS--my debugger is horrible--it doesn't usually work--but if I were
to 'guess' the problem it would be the NumberStyles flags comprise
more than one flag and they are "OR'd" together. As you logic freaks
know, when you "OR" more than two logical flags, you get potential
problems. BUT, I have to point out I got this from MSDN, which had
this example (four flags) AND, no pun intended, you would think they
would have the flags done right so that you can use more than two
flags at the same time. UPDATE: I just tried it with one flag, two
flags and it still fails for the NumberStyles version)

Below is the complete code, cut and paste and it should work to demo
the problem.

See the comments for where the 'error' is. I also am using a
NumberStyles I got from MSDN Help--so it should have worked--but did
not.

Here is the MSDN link for TryParse (similar to Decimal Parse):
http://msdn.microsoft.com/en-us/library/zf50za27.aspx
And here for NumberStyles: http://msdn.microsoft.com/en-us/libr...berstyles.aspx

RL

using System;
using System.Collecti ons.Generic;
using System.Diagnost ics;
using System.Globaliz ation;

namespace Console1
{
class Program
{
static void Main(string[] args)
{
NumberStyles styles = NumberStyles.Al lowParentheses |
NumberStyles.Al lowLeadingSign | NumberStyles.Al lowLeadingWhite |
NumberStyles.Al lowTrailingWhit e;

//PLAIN GENERIC NUMBERSTYLES! WHY DOES C# HAVE TO BE SO DIFFICULT,
WHY, why, Y?

string s1 = "1.23";

decimal d1 = DecimalParse(st yles, s1);

Console.WriteLi ne("s1, d1 are: {0}, {1}", s1, d1); //try
fails, catch thrown. you get d1=0.99 in decimal returned, indicating
the catch block was executed

//now leave out NumberStyles--and see what happens (it works)

decimal d2 = DecimalParse2(s 1);

Console.WriteLi ne("s1, d2: {0}, {1}", s1, d2); //you get
d2=1.23 in decimal returned, correct.
// output:
/*
* parse failed: Input string was not in a correct
format.s1, d1 are: 1.23, 0.99
* s1, d2: 1.23, 1.23
* Press any key to continue . . .
*
* */

// just for shi it s and grins, see if a non-static version makes a
difference (it does not, as I expected)

Program myProgram = new Program();

decimal aDecimal;

aDecimal = myProgram.nonSt atic_DecimalPar se(styles, s1);

Console.WriteLi ne("s1, aDecimal for non-static
DecimalParse: {0}, {1}", s1, aDecimal);
// still fails, like first static example above

//now should succeed, if you leave out NumberStyles

aDecimal = myProgram.nonSt atic_DecimalPar se2(s1);
Console.WriteLi ne("s1, aDecimal for non-static
DecimalParse2: {0}, {1}", s1, aDecimal);
//yes, succeeds to give 1.23, 1.23 as wanted
}

static decimal DecimalParse(Nu mberStyles styles, string
decimalString)
{
try
{
decimal decimalNumber;

decimalNumber = Decimal.Parse(d ecimalString, styles);
Debug.Write("de cimalNumber is: " +
decimalNumber.T oString());
return decimalNumber;

}
catch (Exception ex)
{
// Display the exception message if Parse failed
Console.Write(" parse failed: " + ex.Message);
return 0.99M;
}
} //

// leaving out NumberStyles version of method here:

static decimal DecimalParse2(s tring decimalString)
{
try
{
decimal decimalNumber;

decimalNumber = Decimal.Parse(d ecimalString);
return decimalNumber;

}
catch (Exception ex)
{
// Display the exception message if Parse failed
Console.Write(" parse failed: " + ex.Message);
return 0.69M;
}
} //

decimal nonStatic_Decim alParse(NumberS tyles styles, string
decimalString)
{
try
{
decimal decimalNumber;

decimalNumber = Decimal.Parse(d ecimalString, styles);
Debug.Write("de cimalNumber is: " +
decimalNumber.T oString());
return decimalNumber;

}
catch (Exception ex)
{
// Display the exception message if Parse failed
Console.Write(" parse failed: " + ex.Message);
return 0.99M;
}
} //

decimal nonStatic_Decim alParse2(string decimalString)
{
try
{
decimal decimalNumber;

decimalNumber = Decimal.Parse(d ecimalString);
return decimalNumber;

}
catch (Exception ex)
{
// Display the exception message if Parse failed
Console.Write(" parse failed: " + ex.Message);
return 0.69M;
}
} //
}
}

Sep 2 '08 #1
22 1560
aylopez99 <ra********@yah oo.comwrote:
Here is a classic example of why C# is like beating your head against
the wall.
No, it's an example of the .NET framework not working the way you want
it to. As I've said before, it's important to distinguish between the
language and the framework. C# as a language doesn't know anything
about NumberStyles.

<snip>

Here's a short but complete program showing the actual problem. I had
to do various bits of fixing with your original code due to line
wrapping. It's generally worth posting programs with no lines longer
than 78 characters.

using System;
using System.Globaliz ation;

class Program
{
static void Main(string[] args)
{
NumberStyles styles = NumberStyles.Al lowParentheses |
NumberStyles.Al lowLeadingSign |
NumberStyles.Al lowLeadingWhite |
NumberStyles.Al lowTrailingWhit e;

decimal.Parse(" 1.23", styles);
}
}

It's *much* clearer to just present a program as short as the above and
say, "This is throwing a System.FormatEx ception with the message 'Input
string was not in a correct format' and I don't know why," than to
include the kind of massive program you did.

Now for the actual problem... fix is simple: include
NumberStyles.Al lowDecimalPoint .

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Sep 2 '08 #2
raylopez99 wrote:
Here is a classic example of why C# is like beating your head against
the wall.
You seem to be good at that head beating thing... ;) and once again
there is nothing wrong with the programming language...
I can tell you where the error is in the below code--it's
the "NumberStyl es" property of DecimalParse (which extracts a decimal
from a string)--and how to fix it--you leave it out--but why? WHY?
Y?
Because it's incorrect.
We'll never know... that's just the way it is. Some things were meant
to be...
Well, Jon spotted the problem right away, so now we know...
(PS--my debugger is horrible--it doesn't usually work--but if I were
to 'guess' the problem it would be the NumberStyles flags comprise
more than one flag and they are "OR'd" together. As you logic freaks
know, when you "OR" more than two logical flags, you get potential
problems.
Why do you think that? What potential problems could possibly come from
or:ing more than two values?
BUT, I have to point out I got this from MSDN, which had
this example (four flags) AND, no pun intended, you would think they
would have the flags done right so that you can use more than two
flags at the same time. UPDATE: I just tried it with one flag, two
flags and it still fails for the NumberStyles version)
You obviously took the flags from an example that was parsing an integer
value. If you take example code intended for one purpose and use it for
something different without considering that it may need adjusting,
there is no surprise that it doesn't work as you expect.
Below is the complete code, cut and paste and it should work to demo
the problem.

See the comments for where the 'error' is. I also am using a
NumberStyles I got from MSDN Help--so it should have worked--but did
not.

Here is the MSDN link for TryParse (similar to Decimal Parse):
http://msdn.microsoft.com/en-us/library/zf50za27.aspx
And here for NumberStyles: http://msdn.microsoft.com/en-us/libr...berstyles.aspx

RL
8< snip another bloated piece of example code...

--
Göran Andersson
_____
http://www.guffa.com
Sep 2 '08 #3
The Decimal.TryPars e example would have been better for you to follow. It
includes the AllowDecimal flag that Jon points out you need. I would assume
this is included in the default mode, where you omitted the NumberStyles,
and hence it worked. After all, what's the point of the Decimal type
without a decimal...

"raylopez99 " <ra********@yah oo.comwrote in message
news:e9******** *************** ***********@y38 g2000hsy.google groups.com...
>
Here is the MSDN link for TryParse (similar to Decimal Parse):
http://msdn.microsoft.com/en-us/library/zf50za27.aspx
And here for NumberStyles:
http://msdn.microsoft.com/en-us/libr...berstyles.aspx

RL
Sep 2 '08 #4
"Family Tree Mike" <Fa************ @ThisOldHouse.c omwrote in message
news:uO******** ******@TK2MSFTN GP04.phx.gbl...
After all, what's the point of the Decimal type without a decimal...
Having 28 digits can be useful at times even if you don't bother with the
fractional part.
Sep 3 '08 #5
On Sep 2, 4:16*pm, "Family Tree Mike"
<FamilyTreeM... @ThisOldHouse.c omwrote:
The Decimal.TryPars e example would have been better for you to follow. *It
includes the AllowDecimal flag that Jon points out you need. *I would assume
this is included in the default mode, where you omitted the NumberStyles,
and hence it worked. *After all, what's the point of the Decimal type
without a decimal...
I assumed that the default would include "AllowDecim al", in other
words, that the flags would be more inclusive rather than all-
inclusive.

I was wrong.

Thanks for your help, and sorry to bother you.

In fact, in the actual program, I got rid of these NumberStyles, and
instead depend on an ErrorProvider component to kick in during
Validating event of the forms to catch any errors as the user types
them--much clearer to me, and easier to code.

RL

Sep 3 '08 #6
On Sep 2, 4:07*pm, Göran Andersson <gu...@guffa.co mwrote:
Why do you think that? What potential problems could possibly come from
or:ing more than two values?

Well, what is the result of this:

X AND Y AND Z

where X,Y,Z are 0 or 1 (so you have nine combinations)

consider:

(X AND Y) AND Z

versus

(X) AND (Y AND Z)

versus

X AND Y AND Z

I think it makes a difference. Same for OR, but to a lesser degree
(if at all). Same for XOR. That's why I don' combine more than two
flags at a time.

RL
Sep 3 '08 #7
On Sep 3, 10:57*am, raylopez99 <raylope...@yah oo.comwrote:
On Sep 2, 4:07*pm, Göran Andersson <gu...@guffa.co mwrote:
Why do you think that? What potential problems could possibly come from
or:ing more than two values?

Well, what is the result of this:

X AND Y AND Z

where X,Y,Z are 0 or 1 (so you have nine combinations)

consider:

(X AND Y) AND Z

versus

(X) AND (Y AND Z)

versus

X AND Y AND Z

I think it makes a difference.
Then please show an example. It really doesn't - ditto with OR.

There *is* a difference between
(X OR Y) AND Z
X OR (Y AND Z)
but that's a different matter.

For each bit position, X OR Y OR Z the bit will be set if *any of* X,
Y or Z have that bit set, regardless of bracketing.

For each bit position, X AND Y AND Z the bit will be set if *all of*
X, Y and Z have that bit set, regardless of bracketing.

If bit flags didn't allow more a combination of more than 2
possibilities, they'd be nearly useless.

Jon
Sep 3 '08 #8
On Sep 3, 2:57*am, raylopez99 <raylope...@yah oo.comwrote:
Well, what is the result of this:

X AND Y AND Z

where X,Y,Z are 0 or 1 (so you have nine combinations)
Actually, I made a mistake: it's 27 combinations (3x3x3), some of
which are symmetrical and repeat, but it's a lot of combinations, more
than nine.

RL
Sep 3 '08 #9
On Sep 3, 11:17*am, raylopez99 <raylope...@yah oo.comwrote:
On Sep 3, 2:57*am, raylopez99 <raylope...@yah oo.comwrote:
Well, what is the result of this:
X AND Y AND Z
where X,Y,Z are 0 or 1 (so you have nine combinations)

Actually, I made a mistake: *it's 27 combinations (3x3x3), some of
which are symmetrical and repeat, but it's a lot of combinations, more
than nine.
No, there are 8. If each of X, Y or Z can be 0 or 1, so there are 2 to
the power of 3 combinations. Here they all are, including the result
for X AND Y AND Z:

X Y Z (X AND Y AND Z)
0 0 0 0
0 0 1 0
0 1 0 0
0 1 1 0
1 0 0 0
1 0 1 0
1 1 0 0
1 1 1 1

Jon
Sep 3 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

45
2403
by: Brett | last post by:
If I do this without declaring a corresponding field, is it considered bad design? What are the advantages or disadvantages to either method? Notice there is not set. public string URL { get { return "www.somewhere.com/test.aspx"; }
31
6989
by: Harry Simpson | last post by:
I've come from the old ASP camp where session variables were not used. When i started using ASP.NET in 2001, I started using them again because it was ok from what I'd read. I've been merrily using Session variables for three years now and i'm entering a project with my new boss who has never quite come around that session variables are ok. What's the concensus here. How can i convince him that they are ok in ASP.NET. OR
3
2651
by: Andrew Wrigley | last post by:
Hi, I have a string: "100.00" ....that I want to parse into a decimal. So: decimal d = decimal.Parse("100.00", System.Globalization.NumberStyles.Any) On my dev machine (United Kingdom), this works fine, but on the US server it says that the string is not in the correct format...
41
2348
by: Zytan | last post by:
Anyone do any tests on it? I would assume it has improved since C's rand(), but who knows. For some reason, and it could just be coincidence, I seem to see patterns. But even a crappy rand() function should be good enough to avoid that, so i may be seeing things. Zytan
0
8345
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8857
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8768
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7368
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6186
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5655
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4181
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4348
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1999
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.