Decimals: file read/write when using a text format vs read/write on screen.

Since this caught me out again recently with an old program, I thought I would drop a little post about how to save decimals and display them, and why they can need to be different.

Pi = 3.14159 , right?

Only if you use American , UK or similar regional settings.
Our European friends do things differently, and over there Pi is 3,14159

If you save a decimal value into a text file or XML document, you need to be sure that you can read them back again properly.
(Problems arise if you create a file on a French machine and try to read it back on a US one.
Val(“3,14”) = 3
Val(“3.14”) = 3.14

I find it is best to store as US format everywhere, read as US format from the file, and only worry about the display aspect when displaying on screen.

To do that:

Dim X as double
X = 3.14 //in Xojo code

//Send to a text file…
myfile.writeline Str(x) //stores as 3.14…

//Read from a text file
x = Val( the_string) //expects 3.14 … would be incorrect if it got 3,14

//Display on screen
TextField1.text = CStr(x) //US sees 3.14, France sees 3,14

//get a value from user input
x = Cdbl(TextField1.text )
// correctly converts whatever the user thinks is the right text format.
// French will have entered 3,14 , US will have entered 3.14
// x will be a double holding 3.14 in both cases

If you use a binary format; storing decimals is much easier. ReadDouble & WriteDouble, but binary formats have their own complexities.

Perhaps you could stuff a double into a memoryblock, then base64 the string value of the memoryblock. Make sure you always use the same Endian.