Write a global function called format, which formats numbers with a given number of decimal places. The function accepts a compulsory first argument of type double (the number to be formatted) and a second optional argument of type integer (the number of decimal places) and returns a string object containing the formatted text. If the second argument is missing, the formatting should assume two (2) decimal places. No user-interaction code is allowed in this function.
Write the main function shown below as a test for your function.
#include <iostream>
using std::cout;
using std::endl;
int main()
{
double n1 = 1.24, n2 = 1.25, n3 = 3456.67953;
cout << "'" << format( n1, 1 ) << "'" << endl;
cout << "'" << format( n2, 1 ) << "'" << endl;
cout << "'" << format( n3 ) << "'" << endl;
cout << "'" << format( n3, 3 ) << "'" << endl;
return 0;
}
If the format function is written correctly, the above test should output
'1.2'
'1.3'
'3456.68'
'3456.680'
i've try the following funstion which works but need to use ceil, floor, or trunc
string format(double Value, int nPrecision)
{
char buffer[100]; //Buffer where to store the resulting formatted string.
string s;
switch(nPrecision)
{
case 1:
sprintf(buffer,"%0.1f",Value); //Print formatted data to a string
break;
case 2:
sprintf(buffer,"%0.2f",Value);
break;
case 3:
sprintf(buffer,"%0.3f",Value);
break;
}
s=buffer;
return s;
}
or
string format(double Value, int nPrecision)
{
std::ostringstream ss;
ss.precision(nPrecision);
ss.setf(ios::fixed);
ss << Value;
return ss.str();
}
or this one
string format(double num, int digit)
{
double tmp;
tmp = pow(10,(double)digit);
num=num*tmp;
if((num-abs(num)) > 0.5)
{
num=ceil(num);
}
else
{
num=floor(num);
}
std::ostringstream ss;
ss.precision(digit);
ss.setf(ios::fixed);
ss << num;
return ss.str();
}
but the Output is
12.0
12.0
345668.00
3456680.000