How can I add '+' or '-' before float value using float.ToString() ?

  • Thread starter Thread starter cok119
  • Start date Start date
C

cok119

Hi, all

How can I add '+' or '-' before float value using
float.ToString(fotmat-string) ?
What's the format string should used ?

thanks
 
cok119 said:
Hi, all

How can I add '+' or '-' before float value using
float.ToString(fotmat-string) ?
What's the format string should used ?

thanks

What's wrong with:

String.Format("+{0}", myFloat);

?

Cheers
Chad
 
Chad said:
What's wrong with:

String.Format("+{0}", myFloat);

?

Cheers
Chad

Hi Chad,

What if the float is negative?

This may be better:
String.Format( "{0}{1}", ((myFloat < 0) ? "-" : "+"), myFloat );
 
cok119 said:
How can I add '+' or '-' before float value using
float.ToString(fotmat-string) ?
What's the format string should used ?

Assuming you want the sign of the number to be displayed rather than an
arbitrary '+', then try the following:

a.ToString("+#.###;-#.###;0");

Where 'a' is your variable. This is a format string with sections,
separated by semi-colons. The first section (+#.###) applies to
positive numbers, the second (-#.###) applies to negative numbers and
the last applies to zero.
 
Hi, Bobbo

It work fine, thank you very much :)

Bobbo said:
Assuming you want the sign of the number to be displayed rather than an
arbitrary '+', then try the following:

a.ToString("+#.###;-#.###;0");

Where 'a' is your variable. This is a format string with sections,
separated by semi-colons. The first section (+#.###) applies to
positive numbers, the second (-#.###) applies to negative numbers and
the last applies to zero.
 
Back
Top