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
888 views
in Technique[技术] by (71.8m points)

floating point - How do you round off decimal places in C++?

I need help rounding off a float value to one decimal place.

I know setprecision(x) and cout << precision(x). Both of which work if I wanted to round the entire float, but I am only interested in rounding the decimals to the tenths place.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

There's another solution which doesn't require casting to int:

#include <cmath>

y = floor(x * 10d) / 10d

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

...