Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
643 views
in Technique[技术] by (71.8m points)

c++ - How to truncate a floating point number after a certain number of decimal places (no rounding)?

I'm trying to print the number 684.545007 with 2 points precision in the sense that the number be truncated (not rounded) after 684.54.

When I use

var = 684.545007;
printf("%.2f
",var);

it outputs 684.55, but what I'd like to get is 684.54.

Does anyone knows how can I correct this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What you're looking for is truncation. This should work (at least for numbers that aren't terribly large):

printf(".2f", ((int)(100 * var)) / 100.0);

The conversion to integer truncates the fractional part.

In C++11 or C99, you can use the dedicated function trunc for this purpose (from the header <cmath> or <math.h>. This will avoid the restriction to values that fit into an integral type.

std::trunc(100 * var) / 100     // no need for casts

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...