Vikranth N
Vikranth N

Reputation: 45

How to get a exact decimal precision value without rounding the decimal point value?

I have to convert the double value to CString inorder to display it in the mfc list box. Before displaying it I need to format the decimal points to my required number of digits .

For example here I need to format the double value to 2 digits

double a = 4217.088;        
CString str;
str.Format("%.*lf",2,a); 

Here the assigned value of a is 4217.088. I need the formated str value as 4217.08 but the decimal point value rounds as 4217.09

I also tried with floor method as below but this too gave me the same result.

double b;                                   
b = floor(a * 100) / 100;

Is there any possibilities to format the double value without rounding the decimal points.

Upvotes: 3

Views: 778

Answers (2)

Jabberwocky
Jabberwocky

Reputation: 50778

If you want simple truncation instead of rounding, you can format with 3 decimals and then trunc the result:

double a = 4217.088;   
CString str;
str.Format("%.*lf", 3, a); 
str = str.Left(str.GetLength() - 1);

// str contains now "4217.08"

But this works too:

double a = 4217.088;
str.Format("%.*lf", 2, std::floor(a * 100) /100); 

Upvotes: 1

Santosh
Santosh

Reputation: 1815

Rounding will not work at all. In your case next digit in 8 which greater than 5 hence it's converting next digit to 9. To come to your problem, following code should solve the issue:

double b = std::floor(a * 100.) / 100.;

Upvotes: 2

Related Questions