Skip to content

Commit

Permalink
Change how floats are formatted in MySQL.
Browse files Browse the repository at this point in the history
Fixing precision issues where numbers would get truncated.
Also maintaining compatibility with scientific notation.
Fixes #2049
  • Loading branch information
markstory committed Oct 6, 2011
1 parent a6e4208 commit c143908
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 3 deletions.
2 changes: 1 addition & 1 deletion cake/libs/model/datasources/dbo/dbo_mysql.php
Expand Up @@ -672,7 +672,7 @@ function value($data, $column = null, $safe = false) {
return 'NULL';
}
if (is_float($data)) {
return str_replace(',', '.', sprintf('%G', $data));
return str_replace(',', '.', strval($data));
}
if ((is_int($data) || $data === '0') || (
is_numeric($data) && strpos($data, ',') === false &&
Expand Down
3 changes: 3 additions & 0 deletions cake/libs/model/datasources/dbo/dbo_mysqli.php
Expand Up @@ -188,6 +188,9 @@ function value($data, $column = null, $safe = false) {
if ($data === '') {
return 'NULL';
}
if (is_float($data)) {
return str_replace(',', '.', strval($data));
}
if ((is_int($data) || is_float($data) || $data === '0') || (
is_numeric($data) && strpos($data, ',') === false &&
$data[0] != '0' && strpos($data, 'e') === false)) {
Expand Down
19 changes: 17 additions & 2 deletions cake/tests/cases/libs/model/datasources/dbo/dbo_mysql.test.php
Expand Up @@ -239,10 +239,22 @@ function testLocalizedFloats() {
setlocale(LC_ALL, 'de_DE');

$result = $this->db->value(3.141593, 'float');
$this->assertTrue(strpos((string)$result, ',') === false);
$this->assertEqual('3.141593', $result);

$result = $this->db->value(3.141593);
$this->assertTrue(strpos((string)$result, ',') === false);
$this->assertEqual('3.141593', $result);

$result = $this->db->value(3.141593);
$this->assertEqual('3.141593', $result);

$result = $this->db->value(1234567.11, 'float');
$this->assertEqual('1234567.11', $result);

$result = $this->db->value(123456.45464748, 'float');
$this->assertEqual('123456.454647', $result);

$result = $this->db->value(0.987654321, 'float');
$this->assertEqual('0.987654321', (string)$result);

$result = $this->db->value(2.2E-54, 'float');
$this->assertEqual('2.2E-54', (string)$result);
Expand All @@ -262,6 +274,9 @@ function testScientificNotation() {
$result = $this->db->value(2.2E-54, 'float');
$this->assertEqual('2.2E-54', (string)$result);

$result = $this->db->value(2.2E-54, 'float');
$this->assertEqual('2.2E-54', (string)$result);

$result = $this->db->value(2.2E-54);
$this->assertEqual('2.2E-54', (string)$result);
}
Expand Down

0 comments on commit c143908

Please sign in to comment.