Click here to Skip to main content
14,267,992 members
Rate this:
Please Sign up or sign in to vote.
See more:
How do i convert a double to 2 decimal places and display the output as string or char.

Thanks.
Posted
Rate this:
Please Sign up or sign in to vote.

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:
Please Sign up or sign in to vote.

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:
Please Sign up or sign in to vote.

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:
Please Sign up or sign in to vote.

Solution 3

I would recommend using printf or sprintf
   

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100