Hide
on 19/7/06

Perhaps this will be useful for others.

I needed to be able to convert decimal number to and from the 'local' format. By adding the below methods to my app_model, it is possible to silently convert decimal numbers as they come out of the database to be local format, and vice versa to save. In the code below it is converting numbers of the format 999.999,99 to be 999999.99 - which otherwise would be saved by MySql as 999.99 as the rest of the number is ignored.

  1. <?php
  2. class AppModel extends
  3. Model
  4. {
  5. // Cheat for UTF-8
  6. function __construct()
  7. {
  8. parent::__construct();
  9. $this->execute("Set NAMES 'UTF8'");
  10. }
  11. function afterFind($results)
  12. {
  13. foreach
  14. ($results as $id=>$objectResult)
  15. {
  16. foreach ($objectResult as $class=>$fields)
  17. {
  18. if ($this->name==$class)
  19. {
  20. $classObject = $this;
  21. }
  22. else
  23. {
  24. $classObject = new $class;
  25. }
  26. foreach($classObject->_tableInfo->value as $fieldDetails)
  27. {
  28. $fieldName = $fieldDetails['name'];
  29. $fieldType = $fieldDetails['type'];
  30. if ($fieldType == "float")
  31. {
  32. if (isset($results[$id][$class][$fieldName]))
  33. {
  34. $results[$id][$class][$fieldName] = number_format($results[$id][$class][$fieldName], 2, ',', '.');
  35. }
  36. }
  37. }
  38. }
  39. }
  40. return $results;
  41. }
  42. function
  43. beforeSave()
  44. {
  45. foreach ($this->data as $class=>$fields)
  46. {
  47. if
  48. ($this->name==$class)
  49. {
  50. $classObject = $this;
  51. }
  52. else
  53. {
  54. $classObject = new $class;
  55. }
  56. foreach($classObject->_tableInfo->value as $fieldDetails)
  57. {
  58. $fieldName = $fieldDetails['name'];
  59. $fieldType = $fieldDetails['type'];
  60. if ($fieldType == "float")
  61. {
  62. if
  63. (isset($this->data[$class][$fieldName]))
  64. {
  65. $this->data[$class][$fieldName] = str_replace(array(".", ","), array("", "."), $this->data[$class][$fieldName]);
  66. }
  67. }
  68. }
  69. }
  70. return true;
  71. }
  72. }
  73. ?>

2 Responses to International Number formats

  1. 1
    Thanks alot - just what i needed :)
  2. 2
    Modified version at http://cakephp.org/pastes/show/fb38c3f3db50e10438580f5a098777ab