tamhoang tamhoang - 3 months ago 13
C# Question

C# Convert decimal to string with specify format

I need to convert decimal number a to string b folowing:


  • b must be haven
    '.'
    character. Eg:


    • a = 12 -> b = "12.0"

    • a = 1.2 -> b = "1.2"

    • a = 1.234 -> b = "1.234"




How can I do that with 1 command?


  • b must be haven exactly 10 character. Eg:


    • a = 101 -> b = "101.000000"

    • a = 1.234 -> b = "1.23400000"

    • a = 1.234567891 -> b = "1.23456789"
      Same question with 1)



Answer
decimal number = 12;
var value = number.ToString("N1"); // 12.0

number = 1.2m;
value = number.ToString(); // 1.2

number = 101m;
value = number.ToString("N10"); // 101.0000000000

number = 1.234m;
value = number.ToString("N10"); // 1.2340000000

For the second part of your question - where you want a total length of 10 then:

decimal number = 1.234567891m;
int numberOfDigits = ((int)number).ToString().Length;
var value = number.ToString($"N{9 - numberOfDigits}"); //1.23456789

//Or before C# 6.0
var value = number.ToString("N" + (9 - numberOfDigits)); //1.23456789

Basically ((int)number).ToString().Length gives you the amount of digits before the . (converting to int will remove the fractions) and then reducing that from the number of digits after the . (and also -1 for the decimal point itself)

Comments