2013-02-23 66 views
2

下面是我在做什么:如何比较两个包含小数值的字符串?

if (oss.str() != sValue)

我可以有例如:

2000000000.0002000000000.0

这是相同的值,但不是相同的字符串。我需要比较它的字符串,因为我试图捕获最终溢出sValue

在这种情况下,我可以这样做:

oss << std::setprecison(1) << std::fixed << value;

但问题是一样的,如果我有:

2000000000.12000000000.123

我怎样才能解决呢?

在此先感谢。

+0

是删除所有尾随0的不够,或者你需要像1000.0 == 999.99? – 2013-02-23 19:51:04

+0

@grasGendarme不,我需要知道这些值是否相同。 (完全相同)在你的情况下,条件必须返回false。 – Elfayer 2013-02-23 19:59:15

回答

0

的工作答案:

size_t   i; 

    i = sValue.find('.'); // find the point 
    if (i < sValue.size()) // if there is one, then ... 
    { 
     i = sValue.size() - i - 1; // find the number of decimal 
     oss << std::setprecision(i) << std::fixed << value; // apply the precision 
    } 
    else // otherwise, it's neither a float neither a double 
    oss << std::setprecision(0) << std::fixed << value; // no need of precision 
    if (oss.str() != sValue) 
0

可以使用STRNCMP()函数从

int strncmp(const char *s1, const char *s2, size_t n); 

与c_str()上的std :: string方法和n =分钟(s1.length(),s2.length());

使用整数比较是升压

boost::lexical_cast<int>(s1) == boost::lexical_cast<int>(s2) 

方便的std :: string S1,S2做这项工作。

+0

如果在字符串的开始处得到0,它将不起作用 – 2013-02-23 19:56:51

+0

然后,简单的答案是转换为数字类型并检查相等性。希望你比整数比浮点数。 – Arcturus 2013-02-23 19:58:00

+0

@grasGendarme在字符串的开头不会有0。 – Elfayer 2013-02-23 20:04:43

1

从小数点开始,做两组比较,在每次迭代时解析和比较一个数字,然后到相反的两端。

+0

所以你的意思是手动? – Elfayer 2013-02-23 20:25:01

+0

您可以取小数点前的数字,并将两个长度相同的长度通过预先设定的0添加到较短的一个。在小数点后面,您可以将0添加到较短的一个。每个按字符串比较。并签署检查。 – swtdrgn 2013-02-23 20:37:39

+0

是的,它不是一个或两个班轮(如果我是一个实施这个)。 – swtdrgn 2013-02-23 20:49:28