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
340 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
[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
  • 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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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

Is Your DevOps Pipeline Leaking?

Is your CI/CD pipeline a hodge-podge of randomly connected tools? You’ve likely got a tool to fix one problem & then a different tool to fix another, resulting in a cluster of tools with overlapping functionality. Learn how to optimize your pipeline with Gartner's recommendations

Question has a verified solution.

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

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
In this video we outline the Physical Segments view of NetCrunch network monitor. By following this brief how-to video, you will be able to learn how NetCrunch visualizes your network, how granular is the information collected, as well as where to f…
If you’ve ever visited a web page and noticed a cool font that you really liked the look of, but couldn’t figure out which font it was so that you could use it for your own work, then this video is for you! In this Micro Tutorial, you'll learn yo…

690 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