Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

How to create an ouput decimal value based on a variable length input field using C#?

Posted on 2011-09-22
3
Medium Priority
?
327 Views
Last Modified: 2013-12-17
I am developing a C# console application using Visual Studio 2005.
How would you modify the following code in the code section that follows
to accept an input value of a string of anywhere from 1 to 10 numeric characters and output a decimal value of up to 8 leading numbers followed by a decimal and 2 values
to the right of the decimal representing cents.
I also want to validate that the string of characters read are all numeric
and with a value for the input field greater than zero.
For example:  Input = 0000000035  yields an output value of  .35
                      Input = 0000000135  yields an output value of 1.35





if (reader.Name == "csc:amount")
                        {
                            arr1[i, 9] = "GROUP_FIELD_NAME:CheckAmount";
                            
                            string value = reader.ReadElementContentAsString();

                            if (value.Length >= 2)
                            {
                                Int64 intTest = 0;
                                if (Int64.TryParse(value, out intTest) && intTest > 0)
                                {
                                    arr1[i, 10] = "GROUP_FIELD_VALUE:" + value.Insert(value.Length - 2, ".");
                                    arr1[i, 10] = "GROUP_FIELD_VALUE:" + value;
                                }
                                else
                                {
                                    arr1[i, 10] = "GROUP_FIELD_VALUE:" + value.Insert(value.Length - 2, ".");
                                    sw1.WriteLine("GROUP_FIELD_NAME:ItemSequence:" + itemsequence + ",GROUP_FIELD_NAME:CheckAmount" + "," + "GROUP_FIELD_VALUE:" + value);
                                }
                            }
                            else
                            {
                                arr1[i, 10] = "GROUP_FIELD_VALUE:" + value;
                                sw1.WriteLine("GROUP_FIELD_NAME:ItemSequence:" + itemsequence + " Field CheckAmount has to be a minimum of 2 characters");
                            }                                     
                        }

Open in new window

0
Comment
Question by:zimmer9
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 4

Expert Comment

by:guramrit
ID: 36585209
Your code seems OK.
BTW, check my code:

 
string value = "0000000035";

int intTest = 0;
if (int.TryParse(value, out intTest) && intTest > 0)
{
    value = value.PadLeft(10, '0'); // just to make sure that string has length of 10, other wise add leading zeroes.
    value = value.Insert(value.Length - 2, ".");
    decimal oVal = Convert.ToDecimal(value);

    // do something with 'oVal' like...   

    value = oVal.ToString();

    // now value contains ".35"
}

Open in new window


I think you may be facing problem like value of "value" is not updated after

arr1[i, 10] = "GROUP_FIELD_VALUE:" + value.Insert(value.Length - 2, ".");

because value.Insert() doesn't modify the value of "value", It returns the modified value.
0
 
LVL 33

Accepted Solution

by:
Todd Gerbert earned 2000 total points
ID: 36586404
In your other question (http:/Q_27322878.html#a36584979) I suggested & demonstrated using Double.TryParse() - which is a great way to make sure the user enters a valid number value. If TryParse() returns true, then the double variable passed into TryParse() will contain the numeric value of the string, and you can just use an if (value <= 0) ... to check if the user entered a number that's zero or less.

Double.TryParse(): http://msdn.microsoft.com/en-us/library/system.double.tryparse.aspx

using System;
using System.Text;

class Program
{
	static void Main(string[] args)
	{
		string userInput = String.Empty;
		double value;

		// Get a string from the user that represents a number
		Console.Write("Enter a number: ");
		userInput = Console.ReadLine();

		// Try to convert the string to a double
		if (!Double.TryParse(userInput, out value))
		{
			Console.WriteLine("You didn't enter a valid number. Press any key to exit.");
			Console.ReadKey();
			Environment.Exit(1);
		}

		// Make sure the entered number is greater than zero
		if (value <= 0)
		{
			Console.WriteLine("You entered a number equal to, or less than, zero.");
			Console.Write("Press any key to exit...");
			Console.ReadKey();
			Environment.Exit(2);
		}

		// Divide the number by 100 to put a decimal point
		// two digits in from the right
		value = value / 100;

		// Output the result using Double.ToString()
		Console.WriteLine(value.ToString("0000000000.00"));
		
		// Another way to output the number as string...
		Console.WriteLine("{0:0000000000.00}", value);

		Console.Write("Press any key to exit...");
		Console.ReadKey();
		Environment.Exit(0);
	}
}

Open in new window

0
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 36586410
Ha, I didn't notice you already have TryParse() in your code. ;)

That will check to make sure value is all numeric.
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …

610 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question