PHP String to Float

前端 未结 8 1269
别跟我提以往
别跟我提以往 2020-11-28 05:37

I am not familiar with PHP at all and had a quick question.

I have 2 variables pricePerUnit and InvoicedUnits. Here\'s the code that is set

8条回答
  •  庸人自扰
    2020-11-28 05:52

    Use this function to cast a float value from any kind of text style:

    function parseFloat($value) {
        return floatval(preg_replace('#^([-]*[0-9\.,\' ]+?)((\.|,){1}([0-9-]{1,3}))*$#e', "str_replace(array('.', ',', \"'\", ' '), '', '\\1') . '.\\4'", $value));
    }
    

    This solution is not dependant on any locale settings. Thus for user input users can type float values in any way they like. This is really helpful e.g. when you have a project wich is in english only but people all over the world are using it and might not have in mind that the project wants a dot instead of a comma for float values. You could throw javascript in the mix and fetch the browsers default settings but still many people set these values to english but still typing 1,25 instead of 1.25 (especially but not limited to the translation industry, research and IT)

提交回复
热议问题