473,836 Members | 1,364 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How do i convert a float to string?

24 New Member
hi guys

I am writing a code for to covert expression to string so how is this going to be possible in C?

i know for string to float is using atof() so what about the other way round?

thx
Oct 18 '06 #1
9 196314
vermarajeev
180 New Member
hi guys

I am writing a code for to covert expression to string so how is this going to be possible in C?

i know for string to float is using atof() so what about the other way round?

thx
Here is your solution

Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3.     char* str = new char[30];
  4.  
  5.     float flt = 2.4567F;
  6.     sprintf(str, "%.4g", flt );    
  7.     cout<<str<<endl;
  8.     return 0;
  9. }
Thankx
Oct 18 '06 #2
tyreld
144 New Member
You can use "snprintf" to accomplish this.
int snprintf(char *str, size_t size, const char *format, ...);
Upon successful return, this function returns the number of characters printed (not including the trailing '\0' used to end output to strings). The function snprintf() does not write more than size characters (including the trailing '\0'). If the output was truncated due to this limit then the return value is the number of characters (not including the trailing '\0') which would have been written to the final string if enough space had been available. Thus, a return value of size or more means that the output was truncated. (See also below under NOTES.) If an output error is encountered, a negative value is returned.

You will notice in this example that if you run it the string is reported as truncated. This is because by default the %f format has a percision of 6 decimal places. Change %f to %.2f and rerun it.

Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2.  
  3. #define SIZE 10
  4.  
  5. int main(void)
  6. {
  7.    char buf[SIZE];
  8.    int result = 0;
  9.    float value = 154.78;
  10.  
  11.    result = snprintf(buf, SIZE, "%f", value);
  12.    if (result >= SIZE)
  13.        printf("The string has been truncated\n");
  14.  
  15.    printf("The string value of the floating value = %s\n", buf);
  16.  
  17.    return 0;
  18. }
  19.  
Oct 18 '06 #3
tyreld
144 New Member
Here is your solution

Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3.     char* str = new char[30];
  4.  
  5.     float flt = 2.4567F;
  6.     sprintf(str, "%.4g", flt );    
  7.     cout<<str<<endl;
  8.     return 0;
  9. }
Thankx
Using "sprintf" is a poor choice as it can overrun the provided string buffer if you are careless. Using functions that allow you to control the the size of input copied into a buffer is always the best coding practice. In this case "snprintf" is a better choice.
Oct 18 '06 #4
vermarajeev
180 New Member
I get this error when I use snprintf

error C3861: 'snprintf': identifier not found, even with argument-dependent lookup

I'm using Microsoft Visual Studio .NET on my system

Thankx....
Oct 18 '06 #5
tyreld
144 New Member
I think that it is defined as "_snprintf" on windows.
Oct 18 '06 #6
vermarajeev
180 New Member
I think that it is defined as "_snprintf" on windows.
thankx it works fine.....
Oct 18 '06 #7
srvardhan
1 New Member
Here is your solution

Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3.     char* str = new char[30];
  4.  
  5.     float flt = 2.4567F;
  6.     sprintf(str, "%.4g", flt );    
  7.     cout<<str<<endl;
  8.     return 0;
  9. }
Thankx

There is one easy method using this u can convert from any data type to any other data type

Just include the sstream header file

let
string strSalary = "5449.98";
float SalaryInFloat;

istringstream mySalaray(strSa lary);
mySalaray >> SalaryInFloat

thats it

Rajavardhan Sarkapally
Oct 14 '07 #8
JosAH
11,448 Recognized Expert MVP
There is one easy method using this u can convert from string data type to any other data type

Just include the sstream header file

let
string strSalary = "5449.98";
float SalaryInFloat;

istringstream mySalaray(strSa lary);
mySalaray >> SalaryInFloat

thats it

Rajavardhan Sarkapally
Ern, the OP asked for something the other way around if I'm not mistaken.

kind regards,

Jos
Oct 14 '07 #9
NinjaSkitch
1 New Member
Same basic idea, except using an ostream:

Expand|Select|Wrap|Line Numbers
  1. ostringstream s;
  2. s << 2.5;
  3. cout << s.str();
Nov 27 '07 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

3
10299
by: Convert TextBox.Text to Int32 Problem | last post by:
Need a little help here. I saw some related posts, so here goes... I have some textboxes which are designed for the user to enter a integer value. In "old school C" we just used the atoi function and there you have it. So I enquired and found the Convert class with it's promising ToInt32 method, great... but it doesn't work. The thing keeps throwing Format Exceptions all over the place. What is the "C#" way to do this??? code int wmin,...
4
78804
by: STom | last post by:
How do you convert a string in C# to decimal? STom
15
10843
by: Yifan | last post by:
Hi Does anybody know how to convert System::String* to char*? I searched the System::String class members and did not find any. Thanks Yifan
4
25105
by: Pixie Songbook | last post by:
Hi, I'm trying to write a program using the Dev C++ 4.9.9.2 compiler that takes input numbers from a word document, sums them together, and then gives me a result. It should be easy as the book I have tells me what to do, problem is I get the error message "cannot convert `float' to `float*' for argument `1' to `float array_sum(float*, int)' " for line 22 of the program. This is what I have; #include <iostream.h> #include <fstream.h> ...
3
9205
by: priyanka | last post by:
Hi there, I want to convert a String into integer. I get the string from a file using : string argNum; getline(inputStream,argNum); I now need to convert argNum into integer.
1
369
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - Why does 1+1 equal 11? or How do I convert a string to a number? ----------------------------------------------------------------------- Javascript variables are loosely typed: the conversion between a string and a number happens automatically. Since plus (+) is also used as in string concatenation, '1' + 1 is equal to '11' : the String deciding...
7
6277
by: shellon | last post by:
Hi all: I want to convert the float number to sortable integer, like the function float2rawInt() in java, but I don't know the internal expression of float, appreciate your help!
2
6903
by: lisasahu | last post by:
how to convert float to string like there is atof atoi and itoa but is ther any method to convert float to string
5
3327
by: sidhuasp | last post by:
Hi could anyone please tell me how to convert float value in my database ti HOUR/MIN format for my timesheet requirement. i have to do it in sql-reporting services
3
14570
by: audrey29 | last post by:
How do i convert my string to float?
0
9813
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
9661
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10831
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10582
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10247
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7778
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6976
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5815
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4005
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.