I am searching for a solution to convert a double to a string, but the string should have a comma before the decimal place, not a point.
"One and a half" should look that way 1,5 (german notation).
Thanks for your help!!
I am searching for a solution to convert a double to a string, but the string should have a comma before the decimal place, not a point.
"One and a half" should look that way 1,5 (german notation).
Thanks for your help!!
Unfortunately in VBA, you can't easily write locale-independent code. That is, you can't specify a locale when you take a CStr
cast.
One work around is to convert a double like 0.5 to a string and see what you end up with. If you end up with 0,5
then you're in German (etc.) locale, and you don't need to do anything else.
If you end up with 0.5
then you know you need to make a conversion. Then you just need to traverse your string, replacing dots with commas and vice versa (the vice versa bit is important in case your string has thousands delimiters). You can use Replace
for that.
A combination of CStr and Replace will do the job.
Function Dbl2Str(dbl As Double) As String
Dbl2Str = Replace(CStr(dbl), ".", ",")
End Function
Following RubberDuck comment I ended up with this:
Function DblToStr(x As Double)
DblToStr = CStr(x)
If (Application.ThousandsSeparator = ".") Then
DblToStr = Replace(DblToStr, ".", "")
End If
If (Application.DecimalSeparator = ".") Then
DblToStr = Replace(DblToStr, ".", ",")
End If
End Function
something like this then
Dim somestring As String
Dim someDec As Double
someDec = 1.5
somestring = CStr(someDec)
somestring = Replace(somestring, ".", ",")
MsgBox (somestring)
Select the cells you wish to convert and run this small macro:
Sub changeIT()
For Each r In Selection
t = r.Text
If InStr(1, r, ".") > 0 Then
r.Clear
r.NumberFormat = "@"
r.Value = Replace(t, ".", ",")
End If
Next r
End Sub
Only those cells with "." in them will change and they will be Strings rather than Doubles
I checked the other answers but ended up writing my own solution to convert user inputs like 1500.5
into 1,500.50
, using below code:
'
' Separates real-numbers by "," and adds "." before decimals
'
Function FormatNumber(ByVal v As Double) As String
Dim s$, pos&
Dim r$, i&
' Find decimal point
s = CStr(v)
pos = InStrRev(s, ".")
If pos <= 0 Then
pos = InStrRev(s, ",")
If pos > 0 Then
Mid$(s, pos, 1) = "."
Else
pos = Len(s) + 1
End If
End If
' Separate numbers into "r"
On Error Resume Next
i = pos - 3
r = Mid$(s, i, 3)
For i = i - 3 To 1 Step -3
r = Mid$(s, i, 3) & "," & r
Next i
If i < 1 Then
r = Mid$(s, 1, 2 + i) & "," & r
End If
' Store dot and decimal numbers into "s"
s = Mid$(s, pos)
i = Len(s)
If i = 2 Then
s = s & "0"
ElseIf i <= 0 Then
s = ".00"
End If
' Append decimals and return
FormatNumber = r & s
End Function