I'm doing a dialog application in C++ to calculate something, but I want the result to be with 2 decimal number, how to do this?

here is the function:

void CCalculatorDlg::Oncalc() 
{
	// TODO: Add your control notification handler code here
	
	UpdateData(TRUE);
	
	if ((m_amostras >= 1) && (m_elementos >= 1) && (m_click == true))
	{
		if (m_interno)
			m_total = (19.8522+(3.99038*(m_elementos-1))+((1.74579+((m_elementos-1)*0.1496))*(m_amostras-1))) + (2.5*m_preparacao);
		else if (m_externo)
		{
			if (m_amostras < 11)
				m_total = (19.9519+(19.9519*(m_elementos-1))+((19.9519+((m_elementos-1)*2.494))*(m_amostras-1)))+(5*m_preparacao);
			
			if (m_amostras > 10)
				m_total = (19.9519+(19.9519*(m_elementos-1))+(((19.9519+((m_elementos-1)*2.494))*(9))+((9.98+((m_elementos-1)*2.494))*(m_amostras-10))))+(5*m_preparacao);
		}
	}
	else
	{
		if ((m_amostras < 1) || (m_elementos < 1))	
			MessageBox("Tem que especificar pelo menos uma amostra e um elemento!");
	
		if (!m_click)
			MessageBox("Tem que especificar o tipo de cliente!");
	}
	
	UpdateData(FALSE);
	
}

I want the variable m_total to show with 2 decimal numbers, like, p.e. x,yz.

Thanks

Dani AI

Generated

was right that setprecision is the usual way when you print with streams, and also pointed to the common MFC approach (format a string and put it into the edit control). solved it by binding a CString to the edit control; below are safe, practical options and a small example you can paste into your dialog code (the example uses streams instead of repeating the Format/sprintf snippets already shown).

Keep m_total as a numeric type for calculations. Format only when preparing text for the UI. One cross-build approach is to use the stringstream family so you get fixed rounding and exactly two decimal places:

#include <sstream>

// ANSI build
std::ostringstream oss;
oss.setf(std::ios::fixed);
oss.precision(2);
oss << m_total;
std::string s = oss.str();
m_totalStr = s.c_str();   // m_totalStr is a CString bound to the edit box

// Unicode build (use wostringstream and std::wstring)
std::wostringstream woss;
woss.setf(std::ios::fixed);
woss.precision(2);
woss << m_total;
std::wstring ws = woss.str();
m_totalStr = ws.c_str();

Notes and troubleshooting:

  • If your project is Unicode, prefer std::wostringstream or use CString::Format with the wide format. Some older STL implementations (VC6) behave better with CString::Format.
  • Streams round, they do not simply truncate. If you need truncation instead of rounding, you must apply a floor/trunc operation before formatting.
  • DDX/DDV: binding the control to a double value variable will use default formatting. For precise UI formatting, bind a CString (or set the control text directly with SetDlgItemText) and update it after formatting.
  • If the locale uses a comma as decimal separator, either imbue the stream with the appropriate locale or post-process the string (replace '.' with ',').

This keeps calculations precise and presentation controlled, and it complements the advice already given in the thread.

Recommended Answers

All 6 Replies

Look in

Look in

But I'm not using cout... The variable m_total is shown at the dialog box in an edit box...

you will have to format the string before it is displayed in the dialog box. If you are using MFC, then use CString's Format() method, for exaple

CString text;
float number = 12.123456;
text.Format("%.2f", number);
GetDialogItem(IDC_EDI1)->SetWindowText(text);

If you are not using MFC, then use standard C sprintf() function

char text[20];
float number = 12.123456;
sprintf(text,"%.2f", number);
GetDialogItem(IDC_EDI1)->SetWindowText(text);

I'm using MFC and I tried your exmeple but I get this:

--------------------Configuration: calculator - Win32 Release--------------------
Compiling...
calculatorDlg.cpp
D:\vários\mail\calculator\calculatorDlg.cpp(201) : error C2065: 'GetDialogItem' : undeclared identifier
D:\vários\mail\calculator\calculatorDlg.cpp(201) : error C2227: left of '->SetWindowTextA' must point to class/struct/union
Error executing cl.exe.

calculator.exe - 2 error(s), 0 warning(s)

:sad: Can you figure out why?
thanks

Sorry about the mistake. Should have been GetDlgItem

Alternatively, if you used ClassWizard to assign a CString variable to the edit control, then you don't need to call GetDlgItem() but use that variable instead, then call UpdateData(FALSE) to update the edit control.

If you are new to MFC and you are using VC++ 6.0 compiler you might want to read the Microsoft Scribble tutorial, which will show you how to do all that neat stuff.

Sorry about the mistake. Should have been GetDlgItem

Alternatively, if you used ClassWizard to assign a CString variable to the edit control, then you don't need to call GetDlgItem() but use that variable instead, then call UpdateData(FALSE) to update the edit control.

I've used the alternative you gave me and it works :)
thanks for your attention.

If you are new to MFC and you are using VC++ 6.0 compiler you might want to read the Microsoft Scribble tutorial, which will show you how to do all that neat stuff.

This link it's in my bookmarks :cheesy:
thanks again

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.