views:

591

answers:

3

when i get the money field from sql server to vb.net code, i always get 1.0000 instead of 1.00. how do i convert this to 1.00 in vb.net?

TD = New HtmlTableCell

If Not SqlDR("Price") Is DBNull.Value Then
    TD.InnerHtml = SqlDR("Price")
Else
    TD.InnerHtml = "0.00"
End If

SQLDR is my sql data reader

+1  A: 

That is because SQL Server stores the MONEY field with 4 decimal places. To see it with 2, use the String.Format method.

String.Format("{0:c}", 10) ''result: $10.00

String.Format("{0:N2}", 10) ''result: 10.00

See these pages for more ways to format your numbers

Gabriel McAdams
@Gabriel McAdams: The number of decimal places in SQL Server has *nothing* to do with the number of decimal places which are displayed on output. One can display it with more or less decimal places, if they desired. What matters is the type that the MONEY type in SQL Server is translated to when brought into the .NET space, and even then, how many decimal places the type can hold is irrelevant as one can always add or remove decimal places in the *display*.
casperOne
@Casper: I completely agree.
Gabriel McAdams
@Gabriel McAdams: So why make a reference to that fact in your answer?
casperOne
@Casper: The OP typed `when i get the money field from sql server to vb.net code, i always get 1.0000 instead of 1.00`. The question was how to display it in the way it was expected, rather than how it was returned by SQL Server.
Gabriel McAdams
@Gabriel McAdams: Which is what your answer is lacking. SQL Server doesn't have control over display characteristics, it returns a value which is then transposed onto the .NET type system. Display has nothing to do with it.
casperOne
+1  A: 

You need to format the data when you output it:

myMoney.ToString("0.00");
Mark Byers
+1  A: 

Are you sure you aren't confusing the display of the value with the actual value?

1.0000 and 1.00 are the same value.

If you want to display only a certain number of places when converting a value to a string, you should look at the Custom Numeric Format Strings section in the MSDN documentation to figure out the format string to pass to the ToString method on the Decimal, Double, Single structures, or the static Format method on the String class.

casperOne