c++ - 如何将 double 或 float(所有数字)转换为 int?

标签 c++ floating-point

如何将 double 或 float(所有数字)转换为 int?

例如,如果我有一个 double 0.9332,函数将返回 9332, 1.32001 将返回 132001

最佳答案

this will work ! question is similar to this one :
https://stackoverflow.com/questions/5314954/how-to-get-the-length-of-a-numbers-fraction-part

#include <iostream>
#include <math.h>
using namespace std;
int getFractionDigitsCount(float );
int main()
{
    float a=1.9332;
    int p = getFractionDigitsCount(a);
    cout<<"answer is : "<< a * pow(10,p);

    return 0;
}
 int getFractionDigitsCount(float d) {
    if (d >= 1) { //we only need the fraction digits
        d = d - (long) d;
    }
    if (d == 0) { //nothing to count
        return 0;
    }
    d *= 10; //shifts 1 digit to left
    int count = 1;
    while (d - (long) d != 0) { //keeps shifting until there are no more fractions
        d *= 10;
        count++;
    }
    return count;
}

关于c++ - 如何将 double 或 float(所有数字)转换为 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55016254/

相关文章:

Java 浮点除法的显式类型转换

c - C 中的函数需要有类型吗?

c++ - 在运行时初始化一个 boost::accumulator_set

c++ - 如何获取正则表达式字符串的 AST?

c++ - 内联失败 : function body can be overwritten at link time

c - 如何翻转 double 的指数(例如 1e300->1e-300)?

c++ - is_copy_assignable() 在定义复制赋值时返回 false

c++ - C++的轻量级数据库系统

c - 用于保持浮点值精度的 Printf 宽度说明符

c++ - 如何判断 double float 是否可以安全地存储为单精度 float ?