简体   繁体   中英

Formatting decimal to string of length 9, 2 digits (0 padded) before '.' and 6 after it

I am a newbie in Biztalk and C#, I am trying to format the number in such a way that below requirement can be fulfilled

33.00 -> 33.000000
0.00 -> 00.000000
65.7777777 (random example that results in rounding) -> 65.7777777

So far I am successful with right padding. Below is the code

Param1 = "2.00"
    if (param1.Contains(".")) 
     {
      Decimal convertDecimal = Convert.ToDecimal(param1);
      String temp=convertDecimal.ToString("F6", System.Globalization.CultureInfo.InvariantCulture);
      Console.WriteLine(temp); 
    }

Output: 2.000000 Expected Output: 02.000000

Any idea how can the leading zeros be included?

To add a leading '0' you can use padding or fix your format string to include a leading 0.

As for omitting rounding of 67.77777777777 to 67.7777778 you can format it to one digit more and use string slicing to remove the rounded digit:

using System;

var precision = 7;

// add a leading 0 and add precision + 1 digits after 0
var fmt = $"00.{new string('0', precision + 1)}";

foreach (var param1 in new[]{"0.0","22.00", "77.777777777777"})
{
    Decimal convertDecimal = Convert.ToDecimal(param1);

    String temp = convertDecimal.ToString(fmt);
    Console.WriteLine(temp[..^1]); // temp = temp[..^1]; for later use
}

Output:

00.0000000
22.0000000
77.7777777    # temp is 77.77777778 - the 8 is sliced off the string

If you can not use slicing use string.substring(..) with lenght-1 instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM