在C ++中将64位double转换为int64_t,类似于Convert :: ToInt64方法

时间:2016-12-14 09:16:52

标签: c# c++11 casting double

C ++(g ++编译器)标准库(或其他一些库)中是否有一个函数可以从双精度转换为64位整数,等同于.NET Convert.ToInt64方法中提供的函数?

https://msdn.microsoft.com/en-us/library/fwcsf0k4(v=vs.110).aspx

1 个答案:

答案 0 :(得分:0)

应该只是round()cast

#include <exception>    // std::exception
#include <iostream>     // std::cout
#include <limits>
#include <cstdint>      // int64_t
#include <math.h>       // round

int main(void)
{
    double values[] = { std::numeric_limits<double>::min(), -1.38e10, -1023.299, -12.98,
                       0, 9.113e-16, 103.919, 17834.191, std::numeric_limits<double>::max() };
    int64_t result;

    for (double value : values)
    {
       try {
          result = (int64_t)round(value);
          std::cout << "Converted value '" << value << "' to value " << result << '\n';
       }
       catch (std::exception& e) {
          std::cout << value << " is outside the range of the Int64 type: " << e.what() << '\n';
       }   
    }        
}         

输出:

Converted value '2.22507e-308' to value 0
Converted value '-1.38e+010' to value -13800000000
Converted value '-1023.3' to value -1023
Converted value '-12.98' to value -13
Converted value '0' to value 0
Converted value '9.113e-016' to value 0
Converted value '103.919' to value 104
Converted value '17834.2' to value 17834
Converted value '1.79769e+308' to value -9223372036854775808

Convert.ToInt64()不同,范围违规不会引发异常。 请注意最后一行输出中的转换错误。