从double转换为char或string [英] conversion from double to char or string

查看:154
本文介绍了从double转换为char或string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将双精度数转换为两位小数位并将输出显示为字符串或字符.

谢谢.

How do i convert a double to 2 decimal places and display the output as string or char.

Thanks.

推荐答案

使用标准库简化程序更加通用:
Using the standard library facilitation is simpler and more versatile:
#include<iomanip>
#include<strstream>
#include<string>

// Converts a double to a string rounded to t_digits decimal positions
template <size_t t_digits>
std::string DoubleToString(double dVal)
{
    std::ostrstream oss;
    oss << std::fixed << std::setprecision(t_digits) << dVal << std::ends;
    return oss.str();
}


测试程序:


Test program:

#include<iostream>
int main()
{
    std::cout << DoubleToString<2>(1234.) << std::endl;
    std::cout << DoubleToString<2>(1.1) << std::endl;
    std::cout << DoubleToString<2>(1234.5678) << std::endl;
    std::cout << DoubleToString<2>(1.2345678) << std::endl;
    std::cout << DoubleToString<4>(1.2345678) << std::endl;
}


欢呼声,
AR


cheers,
AR


如果只想在控制台上显示它,则只需:
printf("%.2f\n", doubleVal);

如果要将其分为两部分,只需使用modf函数.

它们确实是两个不同的任务.
If displaying it to the console is the only desire, then just:
printf("%.2f\n", doubleVal);

If you want divide it into two part, just use modf function.

They are indeed two different tasks.


使用modf函数.这会将您的double分为整数部分和小数部分.

然后,取小数部分并乘以10的幂,即10 ^ 2.然后使用floor函数仅返回该数字的整数部分,然后将其除以10的幂.然后,将整数和小数部分加在一起.

use the modf function. This splits your double into the integer part and the fractional part.

Then, take the fractional part and multiply it by a power of 10 in your case, 10^2. Then use the floor function to return just the integer portion of that number and then divide it by the power of 10. Then, add the integer and fractional parts back together.

double dblOriginal, dblIntPortion, dblFractPortion;
dblOriginal = 25.4938;

dblFractPortion = modf(dblOriginal, &dblIntPortion);

dblFractPortion = pow(10.0,2) * dblFractPortion;
dblFractPortion = floor(dblFractPortion);
dblFractPortion = dblFractPortion / pow(10.0,2);

cout << (dblIntPortion + dblFractPortion);



这应该可以为您提供所需的信息(尽管我对C ++有点生锈).



This should give you what you''re looking for (though I''m a bit rusty on c++).


这篇关于从double转换为char或string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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