Search code examples
delphidelphi-10.2-tokyo

How to solve '10,000.00' is not a valid floating point value when even TFormatSetting is set to en-US


I'm trying to get a Double from 10,000.00:

aProductData.BuyPriceHT := 10000;
BuyPriceHTEdit.Text := FormatFloat('#,###.#0', aProductData.BuyPriceHT, FCurrencyFormat);
aProductData.BuyPriceHT := StrToFloat(BuyPriceHTEdit.Text, FCurrencyFormat); <-- error here

where aProductData.BuyPriceHT is a Double

FCurrencyFormat := TFormatSettings.Create('en-US'); 

Note: To the good guys that are going to advice using Decimals or Int64 types to store Currency in db. I already did it is just that it still buggs me why it does not work.


Solution

  • From the documentation of StrToFloat:

    Thousand separators and currency symbols are not allowed in the string.

    Generally speaking, there are so many different ways you can write numbers and dates and times, that you don't want to convert from strings (textual representations) to such values.

    Typically you make sure always to store and transmit such values in numeric form (for instance, as integers, floats, or records of such values), and you only convert such a value to a textual representation when it is to be displayed in a GUI or written to a text file.

    If you need to store or transmit it as text, use a strictly defined format. Then you can write your own converter that interprets that particular format without ambiguity.