C语言 如何在不四舍五入的情况下将浮点值打印到小数点后两位

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19568534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:49:06  来源:igfitidea点击:

how to print float value upto 2 decimal place without rounding off

c

提问by pankanaj

For example I want to print a value in c up to 2 decimal places, without rounding it off.

例如,我想将 c 中的值打印到小数点后 2 位,而不将其四舍五入。

like:

喜欢:

a = 91.827345;
printf("%.2f", a);

will print 91.83, but I want output to be 91.82only. How to do it?

将打印91.83,但我只想输出91.82。怎么做?

回答by Opsenas

i'd suggest shorter and faster approach:

我建议更短和更快的方法:

printf("%.2f", ((signed long)(fVal * 100) * 0.01f));

this way you won't overflow int, plus multiplication by 100 shouldn't influence the significand/mantissa itself, because the only thing that really is changing is exponent.

这样你就不会溢出 int,再加上乘以 100 不应该影响有效数/尾数本身,因为唯一真正改变的是指数。

回答by R.. GitHub STOP HELPING ICE

The only easy way to do this is to use snprintfto print to a buffer that's long enough to hold the entire, exact value, then truncate it as a string. Something like:

执行此操作的唯一简单方法是使用snprintf打印到足够长的缓冲区来保存整个精确值,然后将其截断为字符串。就像是:

char buf[2*(DBL_MANT_DIG + DBL_MAX_EXP)];
snprintf(buf, sizeof buf, "%.*f", (int)sizeof buf, x);
char *p = strchr(buf, '.'); // beware locale-specific radix char, though!
p[2+1] = 0;
puts(buf);