简体   繁体   English

在C ++中将double转换为固定小数点

[英]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. 我在C ++中有一个双变量,并希望将其作为固定的小数点数打印到屏幕上。

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 places)

and simply prints out the required value to standard output (cout). 并简单地将所需的值打印到标准输出(cout)。

Does anyone know how to do this? 有谁知道如何做到这一点?

Thanks in advance. 提前致谢。

假设我正确记住了我的格式字符串,

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

看看setprecision操纵器应该给你的想法

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. convert函数需要是实际打印出来的函数。 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); 如果[decimal places]> 0然后打印小数位,则单独打印每个小数,如: 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 输出:1.23

reference 参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM