How to Format DataGridView Cell

Good Day:

I am creating a WinForms application using VS.NET 2005, VB.NET, and the DataGridView control.  The Unit Price cell on my DataGridView control rounds my number and I do not want the numbers to be rounded.  For example, .375 gets rounded to .38.  How do I format so it does not round the number?  My format code is as follows:

grdDetail.Columns("Unit Price").DefaultCellStyle.Format = "#,###,###.00"

Any Suggestions?
Thank You,
Denise
DeniseGoodheartAsked:
Who is Participating?
 
theplonkConnect With a Mentor Commented:
You can try creating a custom formatter/format provider class by implementing the IFormaterProvider and ICustomFormatter interfaces.

Using the the custom format provider below you can round down a number by setting the "Format" property to "{0:v}" and setting the "FormatProvider" property to "New RoundDownFormatter()".

You can test the below class by running the following:

double number = 0.3366;
            MessageBox.Show(string.Format(new RoundDownFormatter(), "{0:v}", number));

    Public Class RoundDownFormatter
        Implements IFormatProvider, ICustomFormatter
 
        Public Function GetFormat(ByVal formatType As System.Type) As Object Implements System.IFormatProvider.GetFormat
            If (formatType Is GetType(ICustomFormatter)) Then
                Return Me
            End If
            Return Nothing
        End Function
 
        Public Function Format(ByVal format1 As String, ByVal arg As Object, ByVal formatProvider As System.IFormatProvider) As String Implements System.ICustomFormatter.Format
            If (format1 <> String.Empty And arg.GetType() Is GetType(Double)) Then
                If (format1.StartsWith("v")) Then
                    Dim result As Double = Math.Floor(CType(arg, Double) * 100) / 100
                    Return result.ToString()
                End If
            End If
            Return Nothing
        End Function
    End Class

Open in new window

0
 
DeniseGoodheartAuthor Commented:
Hello,

Thank you for posting your code. I was hoping for a simple format code.  There has to be an easier way.
0
 
DeniseGoodheartAuthor Commented:
Hello,

I figured it out.  I simply added an extra 0 at the end as follows:
Me.grdDetail.Columns("Unit Price").DefaultCellStyle.Format = "#,###,###.000"

Cheers,
Denise
0
 
theplonkCommented:
That's no prob. Apologies, i assumed you wanted the value to two decimal places without rounding up.
For any reference to existing standard or custom numeric format specifiers. Just check out:
http://msdn.microsoft.com/en-us/library/427bttx3.aspx
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.