简体   繁体   English

std::to_string(double) 的精度

[英]The precision of std::to_string(double)

使用std::to_string()将 double 转换为字符串时,有没有办法设置结果的精度?

No.不。

Returns: Each function returns a string object holding the character representation of the value of its argument that would be generated by calling sprintf(buf, fmt, val) with a format specifier of "%d" , "%u" , "%ld" , "%lu" , "%lld" , "%llu" , "%f" , "%f" , or "%Lf" , respectively, where buf designates an internal character buffer of sufficient size.返回:每个函数返回一个字符串对象,该对象保存其参数值的字符表示,该对象将通过调用sprintf(buf, fmt, val) ,格式说明符为"%d" , "%u" , "%ld""%lu""%lld""%llu""%f""%f""%Lf" ,其中 buf 指定足够大小的内部字符缓冲区。

I believe that using std::stringstream with setprecision would be the most flexible/portable choice, but if you know your data, as an workaround, you could try to substring the to_string result.我认为,使用std::stringstreamsetprecision将是最灵活的/便携的选择,但如果你知道你的数据,作为一种解决方法,您可以尝试子字符串to_string结果。 For example:例如:

std::string seriesSum(int n)
{
    double sum = 0, div = 1;
    for(int i = 0; i < n; i++) {
      sum += 1.0 / div;
      div += 3;
    }

    return std::to_string(round(sum * 100)/100).substr(0,4);
}

In the code above I'm printing with two decimal places 0.00 by taking the first 4 digits of the string, but it only works because I know the integer part is never going above one digit.在上面的代码中,我通过取字符串的前 4 位数字来打印两个小数位0.00 ,但它仅有效,因为我知道整数部分永远不会超过一位数。 You could also use string.find() to search for the decimal separator and use it's position to calculate the size of the substring, making it a bit more dynamic.您还可以使用string.find()来搜索小数点分隔符并使用它的位置来计算子字符串的大小,使其更具动态性。

I was just looking for a solution to this as I was overloading the std::cout << operator and therefore it would have been tricky to do the std::stringstream workaround.我只是在寻找解决方案,因为我正在重载std::cout <<运算符,因此执行std::stringstream解决方法会很棘手。 I solved my problem by using the std::substr() function to locate the decimal and take a chosen number of digits past it.我通过使用std::substr()函数来定位小数点并在小数点后面选取选定数量的数字来解决我的问题。

std::string trimmedString = std::to_string(doubleVal).substr(0, std::to_string(doubleVal).find(".") + precisionVal + 1);

This will give you "precisionVal" 0's after your number.这将在您的数字后为您提供“precisionVal”0。

Ex:前任:

double doubleVal = 3;
int preisionVal = 2

3.000000 becomes 3.00 3.000000变成3.00

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

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