-3

Please how do I convert a string from 2 decimal places to 5 decimal places in c#?

For example; I'm trying to convert 12.14 to 12.14000 using C#

Donald
  • 73
  • 10

2 Answers2

3

What you're looking for is a ToString() argument:

12.14.ToString("#.00000")

-> "12.14000"

Kanadaj
  • 962
  • 9
  • 25
  • Not if the original value is already a string. – juharr Jul 08 '16 at 14:00
  • @juharr If the original value is already a string then the optimal solution is still parsing it into a float/double and using the argument afterwards. – Kanadaj Jul 08 '16 at 14:02
  • 1
    Actually if the OP knows that the string always has two decimal places then the optimal solution is just concatenating "000" to the end like Jon Skeet mentioned. The problem is that this question is lacking a lot of detail. – juharr Jul 08 '16 at 14:03
  • I'll give you that IF the number is already a string and IF it's always 2 decimal places, then yes. But this is a very specific scenario in mind without accounting for possible abnormalities. – Kanadaj Jul 08 '16 at 14:06
0

Look at PadRight method of String class. MSDN description.

Exaple:

using System;

public class Program
{
    static public void Main()
    {
        string a = "12.14";

        string newA = a.PadRight(8, '0');

        Console.Write(newA);
    }
}

Result:

12.14000

This code always fill to 5 places after point:

using System;

public class Program
{
    static public void Main()
    {
        string a = "332.143";

        int padLen = (5 - (a.Length - a.IndexOf('.') - 1)) + a.Length;

        string newA = a.PadRight(padLen, '0');

        Console.WriteLine(newA);        
    }

}

Result:

332.14300

BWA
  • 5,672
  • 7
  • 34
  • 45
  • That's not going to work because you'd need to pad a different number of zeros based on the values, like "1.22" would need 7 and "122.44" would need 9. And your example of "12.24" would actually need 8 to result in "12.24000". – juharr Jul 08 '16 at 13:59
  • @juharr This is example not solution. I don't want do all homework I want to help. – BWA Jul 08 '16 at 14:03
  • Did you even bother to test it, because as I stated this doesn't even work for the given example. – juharr Jul 08 '16 at 14:06
  • @juharr now works ;-) – BWA Jul 08 '16 at 14:24