在C ++中将双精度转换为固定的小数点 [英] Convert a double to fixed decimal point in C++

查看:110
本文介绍了在C ++中将双精度转换为固定的小数点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中有一个double变量,想将其作为固定的小数点号显示在屏幕上。



基本上我想知道如何写一个函数,该函数使用双精度数和小数位数,然后将数字输出到该小数位数,并在必要时填充零。



例如:

 转换(1.235,2)

将打印出

  1.24 

  convert(1,3)

将打印出来

  1.000 

所以该函数的作用是

  convert(双精度数字,小数位数)

将所需的值打印到标准输出(cout)。



有人知道怎么做吗?



解决方案

假定我正确地记住了格式字符串,

  printf(%。* f,(int )精度((双)数); 


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

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

这篇关于在C ++中将双精度转换为固定的小数点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆