删除 C++ 中的尾随零

问题描述 投票:0回答:7

我想问如何去掉小数点后面的零?

我读过很多有关它的主题,但我不太明白它们。你能告诉我一些简单的理解方法吗?

例如12.50改为12.5,但实际输出是12.50

c++
7个回答
15
投票

恕我直言,这是 C++ 中过于复杂的一件事。无论如何,您需要通过设置输出流的属性来指定所需的格式。为了方便起见,定义了许多操纵器

在这种情况下,您需要设置

fixed
表示形式,并将
precision
设置为 2,以使用相应的操纵器将点后四舍五入到小数点后 2 位,请参见下文(请注意,
setprecision
会四舍五入到所需的精度)。棘手的部分是删除尾随零。据我所知,C++ 不支持开箱即用,因此您必须进行一些字符串操作。

为了做到这一点,我们首先将值“打印”到字符串,然后在打印之前操作该字符串:

#include <iostream>
#include <iomanip>

int main()
{ 
    double value = 12.498;
    // Print value to a string
    std::stringstream ss;
    ss << std::fixed << std::setprecision(2) << value;
    std::string str = ss.str();
    // Ensure that there is a decimal point somewhere (there should be)
    if(str.find('.') != std::string::npos)
    {
        // Remove trailing zeroes
        str = str.substr(0, str.find_last_not_of('0')+1);
        // If the decimal point is now the last character, remove that as well
        if(str.find('.') == str.size()-1)
        {
            str = str.substr(0, str.size()-1);
        }
    }
    std::cout << str << std::endl;
}

1
投票

对于 C++,请检查此 如何在没有科学记数法或尾随零的情况下将浮点数输出到 cout?

使用 printf() 您可以使用以下方法来执行此操作,

int main()
{ 
    double value = 12.500;
    printf("%.6g", value );  // 12.5 with 6 digit precision
    printf("%.6g", 32.1234);  // 32.1234
    printf("%.6g", 32.12300000);  // 32.123
}

1
投票
std::string example = std::to_string(10.500f);   
 while (example[example.size() - 1] == '0' || example[example.size() - 1] == '.')
        example.resize(example.size() - 1);

0
投票

只需使用“printf”函数即可。

printf("%.8g",8.230400);
将打印“8.2304”

float value =4.5300;
printf ("%.8g",value);
将返回 4.53。

试试这个代码。这很简单。


0
投票

我被这个难住了一段时间,不想转换为字符串来完成工作,所以我想出了这个:

float value = 1.00;
char buffer[10];
sprintf(buffer, "%.2f", value);

int lastZero = strlen(buffer);
for (int i = strlen(buffer) - 1; i >= 0; i--)
{
    if (buffer[i] == '\0' || buffer[i]=='0' || buffer[i]=='.')
        lastZero = i;
    else
        break;
}

if (lastZero==0)
    lastZero++;
char newValue[lastZero + 1];
strncpy(newValue, buffer, lastZero);
newValue[lastZero] = '\0';

新值 = 1


0
投票

我在c中寻找同样的问题。这似乎是一个巧妙的解决方案,但我不确定 (d == (int)d) 最终总是为零。

int decDigs(double d) {
    for (int n = 0; ; d *= 10, n++)
        if (d == (int)d) return n;
}
    
void main() {
    for (double d = -1; d; ) {
        scanf("%lf", &d);
        printf("%.*lf\n", decDigs(d), d);
    }
}

-1
投票

您可以将值四舍五入到小数点后 2 位,

x = 下限((x * 100) + 0.5)/100;

然后使用 printf 进行打印以截断任何尾随零..

printf("%g", x);

示例:

double x = 25.528;
x = floor((x * 100) + 0.5)/100;
printf("%g", x);

输出:25.53

© www.soinside.com 2019 - 2024. All rights reserved.