Connecting Tech Pros Worldwide Forums | Help | Site Map

Convert String to float and still retain the precision

Newbie
 
Join Date: Oct 2008
Posts: 3
#1: Oct 29 '08
I am trying to write a method that have this signature in C#
string ConvertFloatToString(float floatNumber, int precision)
if we call ConvertFloatToString (1234.3433,2) then the method should return "1234.34"

Can give me some idea?



tlhintoq's Avatar
Moderator
 
Join Date: Mar 2008
Location: Arizona, USA
Posts: 1,767
#2: Oct 29 '08

re: Convert String to float and still retain the precision


Quote:

Originally Posted by tumblypooh

I am trying to write a method that have this signature in C#

string ConvertFloatToString(float floatNumber, int precision)
if we call ConvertFloatToString (1234.3433,2) then the method should return "1234.34"

Can give me some idea?

This is built into a float type. Use the .ToString() method
Expand|Select|Wrap|Line Numbers
  1.             float bob = 123.456f;
  2.             string szBob = bob.ToString("0.00");
  3.             MessageBox.Show(szBob);
  4.  
Other format samples
iFormatProvider example
Newbie
 
Join Date: Oct 2008
Posts: 3
#3: Oct 29 '08

re: Convert String to float and still retain the precision


Quote:

Originally Posted by tlhintoq

This is built into a float type. Use the .ToString() method

Expand|Select|Wrap|Line Numbers
  1.             float bob = 123.456f;
  2.             string szBob = bob.ToString("0.00");
  3.             MessageBox.Show(szBob);
  4.  
Other format samples
iFormatProvider example

We can use the Convert.ToString() which is the built-in function, we need to invet our own algorithm to implement the method. :(
any thought?
Plater's Avatar
Moderator
 
Join Date: Apr 2007
Location: New England
Posts: 7,161
#4: Oct 29 '08

re: Convert String to float and still retain the precision


This must be a home work assignment type thing then?
Please read the posting guidelines, which covers why we do not answer homework questions
Newbie
 
Join Date: Oct 2008
Posts: 3
#5: Oct 29 '08

re: Convert String to float and still retain the precision


Quote:

Originally Posted by Plater

This must be a home work assignment type thing then?
Please read the posting guidelines, which covers why we do not answer homework questions

This is not a homework assignment as I am not studying but I am a kind of person who is interested in doing programming challenging problem in terms of efficiency.
Plater's Avatar
Moderator
 
Join Date: Apr 2007
Location: New England
Posts: 7,161
#6: Oct 29 '08

re: Convert String to float and still retain the precision


You are not going to get more effecient then the .ToString() method without using unmanaged code.
Reply