What (API?) function can I use to retrieve the decimal separator character from a specific computer (which is defined according to regional settings)?
Printable View
What (API?) function can I use to retrieve the decimal separator character from a specific computer (which is defined according to regional settings)?
Just read the registry value from HKEY_CURRENT_USER\Control Panel\International. The decimal separator is sDecimal.
or ...
MsgBox Mid$(Format$(0.1, "fixed"), 2, 1) & " is the decimal separator on this computer"
Hold on a sec, it should be possible to achieve what you want without knowing what the locale preferences are, you might be making work for yourself. VB has a set of functions that expect/create numerical strings using the locale preferences as well as functions that expect/create using the US default dot.
Here's another function using pure vb code only:
Code:Public Function DecimalSep() As String
DecimalSep = Format$(0.1, ".")
End Function
I'm trying to convert values stored as strings in a text file which represent floating point numbers, i.e. after reading the string I must use CSng(Str) or Val(Str) or CSng(Replace(Str),",",".") or... whatnot.
Whenever I think I've taken care of all possible pitfalls there's always some situation for which my code does not make a correct conversion.
This may be of interest;
Code:Function dpChar$()
dpChar$ = Mid$(Format$(0.1, "fixed"), 2, 1)
End Function
Function Val#(ByVal txt$)
'Wraps VBA.Val
' makes VAL able to handle decimal point chars other than "."
' VBA val only works on decimals when the decimal char is "."
Static normal As Boolean, init As Boolean, dp$
If Not init Then
dp$ = dpChar()
normal = (dp$ = ".")
init = True
End If
If normal Then
Val = VBA.Val(txt$)
Else
Val = VBA.Val(Replace(txt$, dp$, "."))
End If
'VB help recommends use of CDbl but..
'the following does'nt work with strings that contain numbers and text
' like eg. "5.4 mp" because the error is tripped and 0 is returned
'On Error Resume Next
'Val = CDbl(txt$)
End Function
@Magic Ink:
The code you've posted is more or less my intended approach.
Don't forget to remove the thousand separator (if any) before dealing with the decimal separator:
Code:Option Explicit
Public Function DecimalSep() As String
DecimalSep = Format$(0, ".")
End Function
Public Function ThousandsSep() As String
ThousandsSep = Mid$(Format$(1000, "#,#"), 2, 1)
End Function
Public Function Val(ByVal strText As String) As Double
Val = VBA.Val(FixString(strText))
End Function
Private Function FixString(ByVal strText As String) As String
FixString = Replace$(Replace$(strText, ThousandsSep, ""), DecimalSep, ".")
End Function
Private Sub Form_Load()
Debug.Print DecimalSep, ThousandsSep, Val(1234.56)
End Sub
Sorry. Try this:
Code:Public Function ThousandsSep() As String
ThousandsSep = Mid$(Format$(1000, "#,#"), 2, 1)
End Function