0

Hello I might have strings for example "1,1" or "1.1" or "1" or "" and from each of them I need to get results in same format so it can be saved in SQL Db as numeric (8,2)

var ci = CultureInfo.InvariantCulture.Clone() as CultureInfo;
            prikaz.Parameters.AddWithValue("@p_ub_c", Decimal.Parse(p_ub_c.Text.Replace(',', '.') == string.Empty ? "0.00" : p_ub_c.Text, ci));

Passed string is: "2500,00" but can be also "" or "2500.00"

Those values needs to be saved in sql numeric(8,2) And when the textbox p_ub_cis empty then string is 0 and I got this: System.FormatException input string was not in correct format.

May someone help me solve this out?

Thank you for your time

4
  • Sorry, but your question makes no sense. How can 1.1, 1 and an empty string all yield the same result? What value do you want them to all equal? Commented Nov 30, 2013 at 10:31
  • Can we see the actual string passed to the Decimal.Parse? Commented Nov 30, 2013 at 10:31
  • @DavidArno Sorry I mean same formatted result. Commented Nov 30, 2013 at 10:31
  • According to your answer, you didn't understand me, I want you to show the evaluation of - p_ub_c.Text.Replace(',', '.') == string.Empty ? "0.00" : p_ub_c.Text, ci, You should not have , since you replaced them.. Commented Nov 30, 2013 at 10:36

2 Answers 2

2

Your problem lies with the follow code fragment:

p_ub_c.Text.Replace(',', '.') == string.Empty ? "0.00" : p_ub_c.Text

This says 'take my Text and replace "," with ".", then if the result is an empty string, use "0.00", otherwise use Text'. In other words, you lose the result of the Replace.

If you change it to store the results of the Replace and parse that, it should fix the problem. Beware of someone entering eg "1,000.1" though as you'll end up with "1.000.1", which is still an invalid number.

Sign up to request clarification or add additional context in comments.

4 Comments

@DavidAmo THank you but on Windows XP it cannot format. On my Windows 8 its ok. Dont you know how to handle that please?
Sorry @Marek, but I don't understand. What cannot format on XP?
Your code formats well on Windows 8 but on Windows XP it says error converting nvarchar to numeric.
I haven't provided you with any code. I've quoted yours. You need to change it to that supplied by @Yosi in his answer.
2

You never use what Replace returns, you should use it as following:

string.IsNullOrEmpty(p_ub_c.Text) ? "0.00" : p_ub_c.Text.Replace(',', '.');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.