开发者

Convert a double to fixed decimal point in C++

I have a double variable in C++ and want to print it out to the screen as a fixed decimal point number.

Basically I want to know how to write a function that takes a double and a number of decimal places and prints out the number to that number of decimal places, zero padding if necessary.

For example:

convert(1.235, 2)

would print out

1.24

and

 convert(1, 3)

would print out

1.000

so the function works as

convert(number as double, number of decimal plac开发者_C百科es)

and simply prints out the required value to standard output (cout).

Does anyone know how to do this?

Thanks in advance.


Assuming I'm remembering my format strings correctly,

printf("%.*f", (int)precision, (double)number);


Look at the setprecision manipulator which should give you the idea


There is no such thing as a "fixed decimal place" number. The convert function will need to be the function that actually prints it out. I would suggest getting the whole part of the number, then print it. If [decimal places]>0 then print a decimal place, then print each decimal individually like: floor((n*log(10,d))%10); <-- just an idea, not actual code.


#include <iomanip>
#include <iostream.h>

// print a float, x places of precision 
void convert (double number, int x)
{
    cout << setprecision(x) << number << endl;
}

int main()
{
    double a = 1.234;
    convert (a,2);
} 

output: 1.23

reference

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜