14,267,992 members
Rate this:
See more:
How do i convert a double to 2 decimal places and display the output as string or char.

Thanks.
Posted

Rate this:

## Solution 2

Using the standard library facilitation is simpler and more versatile:
```#include<iomanip>
#include<strstream>
#include<string>

// Converts a double to a string rounded to t_digits decimal positions
template <size_t t_digits>
std::string DoubleToString(double dVal)
{
std::ostrstream oss;
oss << std::fixed << std::setprecision(t_digits) << dVal << std::ends;
return oss.str();
}```

Test program:
```#include<iostream>
int main()
{
std::cout << DoubleToString<2>(1234.) << std::endl;
std::cout << DoubleToString<2>(1.1) << std::endl;
std::cout << DoubleToString<2>(1234.5678) << std::endl;
std::cout << DoubleToString<2>(1.2345678) << std::endl;
std::cout << DoubleToString<4>(1.2345678) << std::endl;
}```

cheers,
AR
v3
Rate this:

## Solution 4

If displaying it to the console is the only desire, then just:
`printf("%.2f\n", doubleVal);`

If you want divide it into two part, just use `modf` function.

They are indeed two different tasks.
Rate this:

## Solution 1

use the `modf` function. This splits your double into the integer part and the fractional part.

Then, take the fractional part and multiply it by a power of 10 in your case, 10^2. Then use the `floor` function to return just the integer portion of that number and then divide it by the power of 10. Then, add the integer and fractional parts back together.

```double dblOriginal, dblIntPortion, dblFractPortion;
dblOriginal = 25.4938;

dblFractPortion = modf(dblOriginal, &dblIntPortion);

dblFractPortion = pow(10.0,2) * dblFractPortion;
dblFractPortion = floor(dblFractPortion);
dblFractPortion = dblFractPortion / pow(10.0,2);

cout << (dblIntPortion + dblFractPortion);```

This should give you what you're looking for (though I'm a bit rusty on c++).
v2
Rate this:

## Solution 3

I would recommend using printf or sprintf