Solved

How can modify a field to pad the left side with zeroes so that field is 10 positions plus a decimal point using C#?

Posted on 2011-09-22
9
335 Views
Last Modified: 2013-12-17
I am developing a C# Console application using Visual Studio 2005.
My code is as follows in the code section:

How could I change the code so that the field is padded with zeroes to the left?
The field has to have a minimum length of 2.

For example: value =                  35 (input)
                      value = 00000000.35 (output should be 10 positions plus the decimal point)
 


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, ".");
                                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
  • 3
  • 3
  • 2
  • +1
9 Comments
 
LVL 9

Expert Comment

by:xav056
ID: 36583117
0
 

Author Comment

by:zimmer9
ID: 36583206
The value for the input field titled "value" can be any length between a
a minimum length of 2 and a maximum length of 10.
0
 
LVL 40
ID: 36583370
value = 35; // or any input
value = ( "." + value ).PadLeft(11,'0');
0
 

Author Comment

by:zimmer9
ID: 36583489
Do you mean to modify as follows?
If I do, then initiial value = 0000185512 will result in value = .0000185512

if (value.Length >= 2)
{
          Int64 intTest = 0;
          if (Int64.TryParse(value, out intTest) && intTest > 0)
          {
                value = ("." + value).PadLeft(11, '0');
                 arr1[i, 10] = "GROUP_FIELD_VALUE:" + value;
          }



0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 40
ID: 36583700
Your sample value did not show that there could be zeros in front of the value. By looking closely, maybe you could also have spaces, so lets get rid of both first:

string value = "  000350876"; // or any input that has spaces and/or zeros at the begining
value = ( value.Trim ( ) ).TrimStart ( '0' );
value = ( "." + value ).PadLeft(11,'0');
0
 

Author Comment

by:zimmer9
ID: 36583879
string value = "35"; // or any input that has spaces and/or zeros at the begining
value = ( value.Trim ( ) ).TrimStart ( '0' );
value = ( "." + value ).PadLeft(11,'0');
00000000.35    works fine

However
string value = "0000185512"; // or any input that has spaces and/or zeros at the begining
value = ( value.Trim ( ) ).TrimStart ( '0' );
value = 185512  <---     RESULT
value = ( "." + value ).PadLeft(11,'0');
0000.185512     <----    RESULT     should be 1855.12   WRONG RESULT
0
 
LVL 40
ID: 36584598
You might understand what you need, but you communicate it very badly.

For example: value =                  35 (input)
                      value = 00000000.35 (output should be 10 positions plus the decimal point)

RESULT     should be 1855.12   WRONG RESULT

How come that you want 10 positions for 35, but only 6 for 185512?
How come that you want the extra zeroes on 35, but not on 185512?
Where did you specify that you always wanted only 2 decimals?

If the code you posted was not giving you the results you wanted, if was useless for me to look at it, so I answered to the sample input and output given in the first post. When you told me that this was not good for another input, without telling me the result you wanted, I gave you something that gave the same kind of result for both values. Once again, if your code did not do the work, it was useless for me to try to understand it.

State you needs clearly, and you will have an answer that works for all situations. Keep changing the relation between input and output, or giving incomplete information, and we will be at it for days.
0
 
LVL 33

Accepted Solution

by:
Todd Gerbert earned 500 total points
ID: 36584979
Use Double.TryParse() to convert the string into a number. Divide that number by 100 to put a decimal point two digits in from the right. Double.ToString() can be used to output the number to a string with a specific number of digits.

http://msdn.microsoft.com/en-us/library/system.double.tryparse.aspx
http://msdn.microsoft.com/en-us/library/kfsatb94.aspx

using System;
using System.Collections.Generic;
using System.Linq;
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);
		}

		// 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: 36584989
Output from a couple tests...
Enter a number: 12
User input: 12
Result: 0000000000.12
Press any key to exit...

Open in new window


Enter a number: 123456
User input: 123456
Result: 0000001234.56
Press any key to exit...

Open in new window


Enter a number: 1234567890
User input: 1234567890
Result: 0012345678.90
Press any key to exit...

Open in new window


This one comes out a little funky because the number is so big and the division by 100 results in a weird result - but if your numbers don't ever get this big it shouldn't be an issue.
Enter a number: 1122334455667788
User input: 1122334455667788
Result: 11223344556677.90
Press any key to exit...

Open in new window

0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

747 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now