简体   繁体   English

Round Double 和 Cast to String

[英]Round Double and Cast to String

I suppose this question is a follow up to a previous question I had regarding casting a double to a string.我想这个问题是我之前关于将双精度转换为字符串的问题的后续问题。

I have an API where I'm given a string which represents a number.我有一个 API ,其中给我一个代表数字的字符串。 I need to round this number to 2 decimals of precision and return it as a string.我需要将此数字四舍五入到小数点后 2 位,并将其作为字符串返回。 My attempt to do this follows:我这样做的尝试如下:

void formatPercentCommon(std::string& percent, const std::string& value, Config& config)
{
    double number = boost::lexical_cast<double>(value);
    if (config.total == 0)
    {
        std::ostringstream err;
        err << "Cannot calculate percent from zero total.";
        throw std::runtime_error(err.str());
    }
    number = (number/config.total)*100;
    // Format the string to only return 2 decimals of precision
    number = floor(number*100 + .5)/100;
    percent = boost::lexical_cast<std::string>(number);

    return;
}

Unfortunately the cast captures "unrounded" values.不幸的是,演员表捕获了“未取整”的值。 (ie number = 30.63, percent = 30.629999999999) Can anyone suggest a clean way to round a double and cast it to a string so I get what one would naturally want? (即数字= 30.63,百分比= 30.629999999999)任何人都可以提出一种干净的方法来将双精度数舍入并将其转换为字符串,以便我得到自然想要的东西吗?

Thanks in advance for the help.在此先感谢您的帮助。 :) :)

Streams are the usual formatting facility in C++.流是 C++ 中常用的格式化工具。 In this case, a stringstream will do the trick:在这种情况下,字符串流可以解决问题:

std::ostringstream ss;
ss << std::fixed << std::setprecision(2) << number;
percent = ss.str();

You are probably already familiar with setprecision from your previous post.您可能已经熟悉上一篇文章中的setprecision fixed here is used to make the precision affect the number of digits after the decimal point, instead of setting the number of significant digits for the whole number.此处fixed用于使精度影响小数点后的位数,而不是设置整数的有效位数。

I haven't tested this, but I believe that the following should work:我没有对此进行测试,但我相信以下应该有效:

string RoundedCast(double toCast, unsigned precision = 2u) {
    ostringstream result;
    result << setprecision(precision) << toCast;
    return result.str();
}

This uses the setprecision manipulator to change the precision of the ostringstream that is doing the conversion.这使用setprecision操纵器来更改正在执行转换的ostringstream的精度。

Here's a version that does everything you want without re-inventing the wheel.这是一个无需重新发明轮子即可完成您想要的一切的版本。

void formatPercentCommon(std::string& percent, const std::string& value, Config& config)
{   
     std::stringstream fmt(value);
     double temp;
     fmt >> temp;
     temp = (temp/config.total)*100;
     fmt.str("");
     fmt.seekp(0);
     fmt.seekg(0);
     fmt.precision( 2 );
     fmt << std::fixed << temp;
     percent = fmt.str();
}
double value = 12.00000;

std::cout << std::to_string(value).substr(0, 5) << std::endl;

Converting to a string while creating a substring will truncate extra zeros if you cannot use round() for some reason.如果由于某种原因不能使用round() ,在创建 substring 时转换为字符串将截断多余的零。 I ran into this situation the other day.前几天我遇到了这种情况。

This would come out as 12.00 (don't forget the decimal character!)这将显示为 12.00(不要忘记小数字符!)

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

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