[英]Remove trailing zero in C++
我想问如何去除小数点后的尾随零?
我已经阅读了很多关于它的主题,但我并没有清楚地理解它们。 你能告诉我任何容易理解的方法吗?
例如12.50到 12.5,但实际输出为12.50
这是恕我直言在 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;
}
显而易见的方法是使用setprecision(0)
,例如:
#include <iostream>
#include <iomanip>
int main() {
std::cout << std::setprecision(0) << 12.500 << "\n";
}
std::string example = std::to_string(10.500f);
while (example[example.size() - 1] == '0' || example[example.size() - 1] == '.')
example.resize(example.size() - 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
}
只需使用'printf'功能。 printf("%.8g",8.230400);
将打印“8.2304”
float value =4.5300;
printf ("%.8g",value);
将返回 4.53。
试试这个代码。 这很简单。
我被这件事难住了一段时间,不想转换成字符串来完成工作,所以我想出了这个:
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
您可以将值四舍五入到小数点后 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.