Code: Select all
// d: value to convert
// decimals: number of decimals to output (<= 9)
// usecomma: use the comma as decimal separator if true, otherwise the dot
// thousands_spacer: separate the thousands if true
wxString DoubleToString(double d, int decimals, bool usecomma, bool thousands_spacer)
{
if (decimals > 0) {
double d_int, d_fract;
d_fract = modf(d, &d_int);
wxString s_int, s_fract;
s_int = wxString::Format("%.1f", d_int);
s_int.RemoveLast(2);
if (thousands_spacer)
s_int = FormatThousands(s_int);
switch (decimals) {
case 1: s_fract = wxString::Format("%.1f", d_fract); break;
case 2: s_fract = wxString::Format("%.2f", d_fract); break;
case 3: s_fract = wxString::Format("%.3f", d_fract); break;
case 4: s_fract = wxString::Format("%.4f", d_fract); break;
case 5: s_fract = wxString::Format("%.5f", d_fract); break;
case 6: s_fract = wxString::Format("%.6f", d_fract); break;
case 7: s_fract = wxString::Format("%.7f", d_fract); break;
case 8: s_fract = wxString::Format("%.8f", d_fract); break;
case 9: s_fract = wxString::Format("%.9f", d_fract); break;
}
s_fract.Remove(0, 2); // remove "0." or "0,"
return s_int + (usecomma ? ',' : '.') + s_fract;
} else { // decimals == 0
double fl = floor(d);
double ce = ceil(d);
wxString s;
if (d - fl < ce - d)
s = wxString::Format("%d", (int)fl);
else
s = wxString::Format("%d", (int)ce);
if (thousands_spacer)
return FormatThousands(s);
return s;
}
}
Code: Select all
wxString s;
s = DoubleToString(3.141592, 4, false, false);
// s now contains "3.1416"
s = DoubleToString(3.141592, 4, true, false);
// s now contains "3,1416"
s = DoubleToString(3141.5926535, 3, false, true);
// s now contains "3,141.593"
s = DoubleToString(3141.5926535, 3, true, true);
// s now contains "3.141,593"