Formating a floating point number

  • Thread starter Thread starter Eitan
  • Start date Start date
E

Eitan

Hello,

I have a float point variable defined as: "float floatVar" with the value of
"12.3". I would like to format it using floatVar.ToString() in such a way
that the output will be 1. right aligned and 2. it will have 4 characters
left of the decimal point and 2 right of the decimal point i.e. “ 12.30â€.

Any suggestion how best to do that?

Thanks
EitanB
 
Eitan said:
Hello,

I have a float point variable defined as: "float floatVar" with the value of
"12.3". I would like to format it using floatVar.ToString() in such a way
that the output will be 1. right aligned and 2. it will have 4 characters
left of the decimal point and 2 right of the decimal point i.e. “ 12.30â€.

Any suggestion how best to do that?

Thanks
EitanB

Experiment with something like:

String.Format("{0,-7:0.00}", floatVar)

A bit unsure if that 7 should be positive or negative, but one is
left-aligned, the other is right, and thus padded to be 7 characters.

I think you can use :G2 or a similar syntax as well, to use a format
more in line with your regional settings, just with two decimals.

If the above example doesn't work, dig into the String.Format function
and if you follow the links you'll find something about the format
characters for floating point values.
 
A really simple way would be to use something like...

floatVar.ToString("0.00").PadLeft(7)
 
Lasse said:
Experiment with something like:

String.Format("{0,-7:0.00}", floatVar)

A bit unsure if that 7 should be positive or negative,
positive

I think you can use :G2 or a similar syntax as well,
:F2

If the above example doesn't work, dig into the String.Format function
and if you follow the links you'll find something about the format
characters for floating point values.

http://blog.stevex.net/index.php/string-formatting-in-csharp/ is
better than the MS docs in my opinion.

Arne
 
Back
Top