Currency formatting to save in the database as DECIMAL

10

I am using a mysql database, the field format is Decimal (7,2) and it receives the salary value. Based on what the user types I store in the bank like this:

str_replace(',','.', $_POST['txtSalario'])

Substituting the comma by period. The problem is that if he type ex: 3,145,89, the database refuses because he understands that the first point is already the decimal place. How to handle this data entry to receive values typed as 3145.89 or 3.145.89? I'm using PHP 5.3 and mysql 5.5

    
asked by anonymous 06.02.2014 / 13:21

5 answers

8

In the input field of the edit screen you have to replace the semicolon, so that when saving the function below, do not give an error.

On the edit screen:

$valor = $valor = str_replace('.', ',',$NumValorDeconto);

And to save I used a function to clean.

public static function moeda($get_valor) {

        $source = array('.', ',');
        $replace = array('', '.');
        $valor = str_replace($source, $replace, $get_valor); //remove os pontos e substitui a virgula pelo ponto
        return $valor; //retorna o valor formatado para gravar no banco
    }
    
06.02.2014 / 14:06
4

I did not test the code, but have you tried removing the dot before?

str_replace(',','.', str_replace('.','', $_POST['txtSalario']))
    
06.02.2014 / 13:33
0

Because money needs an exact representation, do not use data types that are only approximated as float . You can use a fixed-point numeric data type, such as

numeric(15,2)

15 is the precision (total length of value, including decimals) 2 is the number of digits after the decimal point See Types numbers in MySQL :

These types are used when it is important to preserve accuracy, such as monetary data.

to validate use something like:

preg_match('!^\d{1,3}(\.\d{3})*(\,\d{2})?$!', $number) || preg_match("!^\d+,\d\d$", $number);
    
06.02.2014 / 13:37
0

I had this problem and solved it using a different approach on the input form.

Instead of having a single input for a float, divide it into two inputs: one for the integer value and one for the decimal value. Make the decimal value default to 00. In this case, you ensure that the value will always be divided between the integer value and the decimal places, and is easier to manipulate later on the server side.

JSFiddle

    
06.02.2014 / 20:08
0

Friend you probably solved it of course né ... rs more I know that someone will fall in this page doing the same research are follows a simple and functional code!

  function Valor($valor) {
       $verificaPonto = ".";
       if(strpos("[".$valor."]", "$verificaPonto")):
           $valor = str_replace('.','', $valor);
           $valor = str_replace(',','.', $valor);
           else:
             $valor = str_replace(',','.', $valor);   
       endif;

       return $valor;
}
    
25.01.2017 / 08:56