So I'm trying to write this time keeping code for a project of mine. Basically, I'm adding 0.01 to a variable over and over again.

While (A < B) {
X = X + 0.01
A = A + 1
}

I have written down the basic idea. The problem I'm encountering is that after I get into very high numbers, things start to get weird; like finding numbers in the thousandths place, numbers taken out before the decimal, and what not. I think that I may be pushing the limit to what float and double variables can hold...

So if any of you could help me make a counter that's correct or very accurate, I'd be appreciative.

## All 6 Replies

That's scientific notation you're seeing, because the variable type you're using can't hold the numbers you're trying to store.

Well what variable type or format should I use then?

How big are the values we're talking about? Many doubles can go out to something like +/- 1.7 E +/- 308.

You could try a long double, but many compilers implement them the same as a regular double. Without going to an external library specifically designed for extremely large (or small) numbers you really don't have many options.

Float is to short
What double is to long

A float stores 1/2 the bits of a double
A double is a 64bit number, a float is 32bits like an int, but some of its storage is used for the decimal point.

Use double, although with a number as small as 1000 or even 10,000, I highly doubt float would give you any problems.

I've said it before -- I'll say it again... Jeez!!!

The problem you are having is with the digital limitations of floating point values. They are not exact. When you keep adding 0.01 to a value, a small error will creep in because floating point cannot represent all numbers with precision -- it's the problem with digital representations. The 'thousandths' you see is just such an error.

If your precision is 0.01 then this error is negligible so you don't really have to worry about it. Just limit the output to 2 decimals.

If your precision is 0.01 then this error is negligible so you don't really have to worry about it. Just limit the output to 2 decimals.

Not quite. The result would depend on the magnitude of the number involved and the number of significant digits in the mantissa of the floating point representation that is used.

Try this:

``````std::cout << std::fixed << std::setprecision(2) ;
for( double a = 1.0 ; a < 1.0e+30 ; a *= 10.0 )
{
double b =  a + 0.01 ;
std::cout << a << ' ' << b << ' ' << b-a << '\n' ;
}``````
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.