I have a string
which needs a decimal place inserted to give a precision of 2.
3000 => 30.00
300 => 3.00
30 => .30
Given a string input, convert to integer, divide by 100.0 and use String.Format() to make it display two decimal places.
String.Format("{0,0:N2}", Int32.Parse(input) / 100.0)
Smarter and without converting back and forth - pad the string with zeros to at least two characters and then insert a point two characters from the right.
String paddedInput = input.PadLeft(2, '0')
padedInput.Insert(paddedInput.Length - 2, ".")
Pad to a length of three to get a leading zero. Pad to precision + 1 in the extension metheod to get a leading zero.
And as an extension method, just for kicks.
public static class StringExtension
{
public static String InsertDecimal(this String @this, Int32 precision)
{
String padded = @this.PadLeft(precision, '0');
return padded.Insert(padded.Length - precision, ".");
}
}
// Usage
"3000".InsertDecimal(2);
Note: PadLeft() is correct.
PadLeft() '3' => '03' => '.03'
PadRight() '3' => '30' => '.30'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With