获取小数点值

时间:2011-10-07 14:55:38

标签: c++ double

我有一个功能,应该将double值转换为string一个:

inline static string StringFromNumber(double val) // suppose val = 34.5678
{
 long integer = (long)val; // integer = 34
 long pointPart; // should be = 5678  how do I get it?
}

如何为longinteger获取pointPart值?

添加:我希望精确到17个数字,并丢弃零。更多例子:

  

val = 3.14 integer = 3 pointPart = 14

     

val = 134.4566425814748 integer = 134 pointPart = 4566425814748

到目前为止我还没有任何解决方案。我怎么能得到它?

3 个答案:

答案 0 :(得分:3)

字符串流特别不会得到小数点,但它会将整个数字转换为字符串。

std::stringstream ss;
ss << val;
/*access the newly-created string with str()*/
return ss.str();

答案 1 :(得分:2)

long pointPart = static_cast<long>(val*10)%10;

10小数点后2位... 100比3等...

String realPoint = (string)pointPart;

加上long connot持有17位数字。它拥有10。 所以你可能想要一个浮点变量

答案 2 :(得分:1)

您可以使用modf分隔整数和小数部分。然后,您可以将小数部分乘以1.0e17,并调用floor以将结果正确地舍入为其整数分量,然后转换为unsigned long(小数部分永远不会为负数,这允许您最大化整数类型中的位数)。最后运行一个循环来修剪unsigned long上的零。例如:

inline static string StringFromNumber(double val)
{
    double intpart, fracpart;
    fracpart = round((modf(val, &intpart)) * 1.0e17);

    long int_long = static_cast<long>(intpart);
    unsigned long frac_long = static_cast<long>(fracpart);

    //trim off the zeros
    for(unsigned long divisor = 10;;divisor *= 10)
    {
        if ((frac_long / divisor) * divisor != frac_long)
        {
            frac_long = frac_long / (divisor / 10);
            break;
        }
    }

    //...more code for converting to string
}

请注意,如果您使用的是64位平台,并且unsigned long被定义为64位整数类型,则此代码最多只能工作17位小数。否则,您需要将unsigned long更改为uint64_t。另请注意,由于浮点数是近似值,并且乘数是1.0e17,因此fracpart的值可能不完全是val的点部分的值。换句话说,在任何必要的舍入后可能会有一些额外的数字。

相关问题