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
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
338 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
Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

 

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
 
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 Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

Question has a verified solution.

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

Suggested Solutions

This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…

840 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