C language converts floating-point data into strings

Source: Internet
Author: User


In your program, you may encounter the need to convert floating-point data to a string:

  #include <stdio.h>void float2char (float,char*,int); Int main () {     Char buffer[10];    float2char (123.4567,buffer,10);     printf ("%f   Convert to String  %s\n ", 123.4567,buffer);     float2char ( -654.321,buffer,10);     printf ("%f  converted to string  %s\n", -654.321,buffer);     return 0;} Void float2char (float slope,char*buffer,int n)   //floating-point number, the stored character array, the length of the character array {     int temp,i,j;    if (slope>=0)//judgment is greater than 0         buffer[0] =  ' + ';    else    {         buffer[0] =  '-';         slope = -slope;    }    temp =  (int) slope;//Rounding number part     for (i=0;temp!=0;i++)//calculates the number of digits in the integer part         temp /=10;     temp = (int) slope;    for (j=i;j>0;j--)//Convert integer part to string     {         buffer[j] = temp%10+ ' 0 ';         temp /=10;    }    buffer[i+1] =   '. ';     slope -= (int) slope;    for (i=i+2;i<n-1;i++)//Convert fractional parts to string type     {        slope*=10;         buffer[i]= (int) slope+ ' 0 ';         slope-= (int) slope;    }    buffer[n-1] =  ' + ';}

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M01/5B/24/wKioL1UAXiHBu1NfAACS5EGgHmo605.jpg "title=" 1.png " alt= "Wkiol1uaxihbu1nfaacs5egghmo605.jpg"/>

This article is from the "Useless Uncle" blog, please be sure to keep this source http://aslonely.blog.51cto.com/6552465/1619533

C language converts floating-point data into strings

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.