Skip to content

Convert string to double does not work on computers with certain locales #1

@alexandrehtrb

Description

@alexandrehtrb

Hello,

I am using VbscriptJSONLib for handling JSONs in VBScript, and I had a bug that floating-point numbers in JSONs were not parsed correctly in my computer.

After debugging, I found out that it was because VBScript CDbl() function parses doubles using the system locale. If the locale uses commas as separators for decimal places, then numbers that use dots as separators, as the default is in JSON, would not be parsed correctly.

To fix the problem, I added a function to VbscriptJSONLib.vbs and changed the parseNumber() function:

parseNumber = ConvertToDoubleLocaleIndependent(Value)

...

'
' Convert string to double, independent of system locale
' Doubles and floats can be represented both with commas or dots, such as: 12.3 or 12,3
' In US locale, floating-point numbers use dots as separators
' But other locales, like Brazil, use commas as separators for decimal places
' In JSON, floating-point numbers always use dots as separators
'
Private Function ConvertToDoubleLocaleIndependent(ByRef str)
	Dim systemSeparator: systemSeparator = Mid(FormatNumber(0.1, 1, True, False, -2), 2, 1)
	If systemSeparator = "," Then
		ConvertToDoubleLocaleIndependent = CDbl(Replace(str,".",","))
	Else
		ConvertToDoubleLocaleIndependent = CDbl(str)
	End If
End Function

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions