0
\$\begingroup\$

I have a requirement to format all my string to the format ##.###/##.### Example: If input value is 3/4 then i need to format it to 03.000/04.000 If my input value is 1.4/2.0 then i need to format it to 01.400/02.000 I have tried the below, which is giving the expected output. Can someone suggest is there any direct function or better way to do this.

using System; 
class Test { 
// Main Method 
static void Main(string[] args) 
{ 
    
    String input = "23.3/4.0"; 
    String[] splittedValue = input.Split('/'); 
    Decimal numerator=Convert.ToDecimal(splittedValue[0]);
    Decimal denominator=Convert.ToDecimal(splittedValue[1]);
    String format = "00.000";
    String test1  =  numerator.ToString(format);
    String test2 =  denominator.ToString(format);
    
}
}
\$\endgroup\$
3
  • 1
    \$\begingroup\$ Welcome to CodeReview. What is the scope of your question? The program or the string formatting pattern? \$\endgroup\$ Commented Mar 22, 2021 at 12:29
  • \$\begingroup\$ String formatting pattern \$\endgroup\$
    – Devi
    Commented Mar 22, 2021 at 12:33
  • 1
    \$\begingroup\$ No, I don't think so there is a shorter / more concise way to convert 1.4 to 01.400. With N3 you could add precision like 1.400 but without leading zero. With PadLeft you could add leading zero, but now you would have two operations instead of one. \$\endgroup\$ Commented Mar 22, 2021 at 12:39

1 Answer 1

2
\$\begingroup\$

One way of being more concise is to split the string by '/' and '.'and rebuild the 2 strings with padding. This eliminates 2 conversions and gives the required format:

static void Main(string[] args) 
{ 
    
    var input = "23.3/4.0";
    var splittedValue = input.Split( '/', '.' );
    var num = FormatFracParts( splittedValue[0], splittedValue[1] );
    var den = FormatFracParts( splittedValue[2], splittedValue[3] );
    
}

private static string FormatFracParts(params string[] parts)
{
    if(parts.Length != 2)
    {
        throw new ArgumentException( @"'parts' must have exactly 2 elements." );
    }
    return $"{parts[0].PadLeft(2, '0')}.{parts[1].PadRight(3, '0')}";
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.