I need to round a double to the nearest valid uint64_t
.
So
uint64_t Round(double);
Round(std::numeric_limits<double>::max())==std::numeric_limits<uint64_t>::max();
Round(std::numeric_limits<double>::lowest())==std::numeric_limits<uint64_t>::min();
Round(1.1)==1;
The Round should be equivalent this to but for uint64_t rather than signed integral
auto Round(double d){
std::fesetround(FE_TONEAREST);
return llrint(d);
}
Are there any functions in std && boost to enable this?
A double
cannot hold all the values of uint64_t
, since both are usually 64-bits and the double
needs to set aside bits for the exponent.
However, it's not too hard to get the closest value:
uint64_t Round(double x){
double rounded=round(x);
if(rounded<0)
return 0;
if(rounded>=pow(2,64))
return std::numeric_limits<uint64_t>::max();
return static_cast<uint64_t>(rounded);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.