Click here to Skip to main content
16,017,922 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How do i convert a double to 2 decimal places and display the output as string or char.

Thanks.
Posted

Using the standard library facilitation is simpler and more versatile:
C++
#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:
C++
#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
 
Share this answer
 
v3
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.
 
Share this answer
 
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.

C
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++).
 
Share this answer
 
v2
I would recommend using printf or sprintf
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900