Reputation: 3967
I know there are plenty of question about this but I ddn't found anything reggarding this.
I try to format number following this format : value.ToString("N", new CultureInfo("fr-CA")). The type of value is float. The format apply but not the way I tought it would. I refered to this article about formatting
Here exemples :
123456 display as 123 456.00
123456.789 display as 123 456.79 // rounded
1234.5 display 1 234.50 //added a 0 padding
Is there a way to format somthing like this ?
123456 display as 123 456
123456.789 display as 123 456.789
1234.5 display as 1 234.5
Here is the code were I try to apply the formatting
private void dgvform_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
float val;
if ( (e.ColumnIndex == valeur.Index || e.ColumnIndex == valeurEN.Index)
&& dgvform.Rows[e.RowIndex].Cells[type_d.Index].Value != null && dgvform.Rows[e.RowIndex].Cells[type_d.Index].Value.ToString() == "N"
&& dgvform.Rows[e.RowIndex].Cells[valeur.Index].Value != null
&& float.TryParse(dgvform.Rows[e.RowIndex].Cells[valeur.Index].Value.ToString(), out val))
{
if (e.ColumnIndex == valeurEN.Index)
e.Value = val.ToString("N", new CultureInfo(_formatEN));
else
e.Value = string.Format("{0:# ### ###.####}", val);
}
}
this is part of a datagridview. the big if
is to determinate if I need to apply formatting to this cell. valeur
, valeurEN
are both column were I need to apply formating. e.Value = val.ToString("N", new CultureInfo(_formatEN));
is the old way I apply the formatting. _formatEN
is basically "en-US".
Basically I want to add a thousand separator and be sure to use the good decimal separator any tought about what i'm doing wrong?
/edit : value is a type of float
Upvotes: 1
Views: 85
Reputation: 54877
I assume you would need to build a custom numeric format string.
value.ToString("#,0.##########", new CultureInfo("fr-CA"))
The leading #,0
part introduces the thousands separator, whilst the trailing .###…
adds as many fractional digits as is required (up to a maximum corresponding to the number of #
characters you specified). The ,
and .
specifiers are not used verbatim, but interpreted according to the current culture.
Refer to http://ideone.com/QypZBP for a sample run:
double d = 12345.6789;
Console.WriteLine(d.ToString("#,0.##########", new CultureInfo("fr-CA")));
// Output: "12 345,6789"
Edit: Since you've clarified that you're using a float
, then the reason why the last digits are getting truncated is due to the limited precision of that data type. Per MSDN, float
has a precision of 7 digits, meaning that the last two digits are never even stored in your variable. If you want to be able to represent your number, you should change your data type to double
.
Upvotes: 1