The most efficient way to convert a string to 2 decimal places in C #

I have stringone that needs a decimal place to get an accuracy of 2.

3000 => 30.00
 300 =>  3.00
  30 =>   .30
+3
source share
3 answers

To enter a string, convert to an integer, divide by 100.0 and use String.Format () to display two decimal places.

String.Format("{0,0:N2}", Int32.Parse(input) / 100.0)

Smarter and without conversion back and forth - draw a string with zeros with at least two characters, and then insert two letters to the right.

String paddedInput = input.PadLeft(2, '0')

padedInput.Insert(paddedInput.Length - 2, ".")

Pad three in length to get an initial zero. Pad for accuracy + 1 in the extension method to get the initial zero.

And as an extension method, just for bumps.

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'
+14

tryParse, .

int val;

if (int.Parse(input, out val)) {
    String.Format("{0,0:N2}", val / 100.0);
}
0

.. urValue.Tostring( "F2" )

let's say .. int / double / decimal urValue = 100; urValue.Tostring ("F2"); the result will be "100.00"

so F2 - how many decimal places u want if you want 4 place, then use F4

0
source

Source: https://habr.com/ru/post/1705812/


All Articles