Hi,
How can I take a number like 3.243434 and format it so that the returned value is 3.24
Thanks
Printable View
Hi,
How can I take a number like 3.243434 and format it so that the returned value is 3.24
Thanks
A quick and dirty solution is to multiply it by 10^(number of decimal places), cast to an integer, then cast back to a float and divide by 10^(number of decimal places). However, this will fall over on accurate conversion, since it will merely truncate rather than use the last digit correctly. So, you need to add 5 * 10^(-places):
I think...you'd have to test it :)Code:float num = 3.46564;
int places = 2;
float pow10 = pow(10, places);
num = (float)((long)(num * pow10));
num += 5 * (1.0f / pow10);
num /= pow10;
Code:
#include <stdio.h>
#include <stdlib.h>
double fNum(double n,unsigned int places);
float fNum(float n,unsigned int places);
void main()
{
double d = 83.010903;
double dFormated;
float f = 123.456f;
// Double's
// print the number
printf("%f \n",d);
// print the number formated
printf("%.1f \n",d);
printf("%.2f \n",d);
printf("%.3f \n",d);
printf("%.4f \n",d);
printf("%.5f \n",d);
// format the number
dFormated = fNum(d,5);
printf("%f \n",dFormated);
// Floats
printf("%f \n",f);
f = fNum(f,2);
printf("%f \n",f);
}
double fNum(double n,unsigned int places)
{
int decimal, sign;
char b[20]; // buffer
char *e; //extra
_ecvt(n,places,&decimal,&sign);//get the number digits before Decimal point
char * s = _gcvt(n, decimal + places, b); // convert it to string
n = strtod(s,&e);
return (n);// convert it to double and return
// when the number is returned it adds zeros on the end,
// I don't know why it does this!
}
float fNum(float n,unsigned int places)
{
// same thing but floats!
int decimal, sign;
char b[20];
char *e;
_ecvt(n,places,&decimal,&sign);
char * s = _gcvt(n, decimal + places, b);
n = (float)strtod(s,&e);
return (n);
}
Thanks to the both of you