Skip to content

Commit

Permalink
Init commit
Browse files Browse the repository at this point in the history
  • Loading branch information
alglyzin committed Nov 29, 2020
1 parent dbf71d0 commit 738c721
Show file tree
Hide file tree
Showing 5 changed files with 137 additions and 0 deletions.
11 changes: 11 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Created by .ignore support plugin (hsz.mobi)
### Composer template
composer.phar
/vendor/
/.idea
/composer.lock

# Commit your application's lock file https://getcomposer.org/doc/01-basic-usage.md#commit-your-composer-lock-file-to-version-control
# You may choose to ignore a library lock file http://getcomposer.org/doc/02-libraries.md#lock-file
# composer.lock

44 changes: 44 additions & 0 deletions README
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# Реализация [JSON_FLOAT_AS_STRING](https://wiki.php.net/rfc/json_numeric_as_string) для json_decode

Когда вы имеете дело с финансами, очень важно не потерять точность при декодировании json строки с помощью ```json_decode()```. Единственное обходное решение, - это использовать ```preg_replace``` для добавления кавычек в исходную строку JSON. Данный метод ```Json::float_safe($string)``` позволяет это сделать.

- Не изменяет структуру самого JSON (пробелы, переносы...)
- Обрамляет кавычками экспоненциальный формат числа
- Работает достаточно быстро

### Пример использования:

```php
<?php

require __DIR__ . '/../vendor/autoload.php';

use alglyzin\Json\Json;

$json = ' {
"a": 0.00000001e23,
"b": 0.00000001,
"c": 10000000000.0e+45,
"d": 0.00000001e-3,
"e": 10.0E4,
"f": 1000000000.0E-34,
"g": 0.000000000000001,
"h": 100000
}';

$json = Json::float_safe($json);

echo $json;

// echo $json:
// {
// "a": "0.00000001e23",
// "b": "0.00000001",
// "c": "10000000000.0e+45",
// "d": "0.00000001e-3",
// "e": "10.0E4",
// "f": "1000000000.0E-34",
// "g": "0.000000000000001",
// "h": 100000
// }
```
22 changes: 22 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"name": "alglyzin/json",
"description": "Convert all float values to string when decoding JSON string",
"minimum-stability": "stable",
"license": "GPL-3.0-only",
"version": "1.0.0",
"authors": [
{
"name": "Andrey Glyzin",
"email": "btpahce@gmail.com"
}
],
"require": {
"php": ">=5.6.0",
"ext-json": ">=1.2.0"
},
"autoload": {
"psr-4": {
"alglyzin\\Json\\": "src/"
}
}
}
32 changes: 32 additions & 0 deletions examples/example.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

require __DIR__ . '/../vendor/autoload.php';

use alglyzin\Json\Json;

$json = ' {
"a": 0.00000001e23,
"b": 0.00000001,
"c": 10000000000.0e+45,
"d": 0.00000001e-3,
"e": 10.0E4,
"f": 1000000000.0E-34,
"g": 0.000000000000001,
"h": 100000
}';

$json = Json::float_safe($json);

echo $json;

// echo $json:
// {
// "a": "0.00000001e23",
// "b": "0.00000001",
// "c": "10000000000.0e+45",
// "d": "0.00000001e-3",
// "e": "10.0E4",
// "f": "1000000000.0E-34",
// "g": "0.000000000000001",
// "h": 100000
// }
28 changes: 28 additions & 0 deletions src/Json.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

namespace alglyzin\Json;

class Json
{

/**
* Превращаем числа с плавающей запятой в строки для предотвращения потери или искажения
* точности при декодировании строки с помощью json_decode()
* @param string $json
* @return string
*/
public static function float_safe($json)
{
$regexp = '/"(\s*)\:(\s*)(\-?\d+([eE][\+|\-]?\d+|\.\d+)+)(\s*[,(\s*)|\}])/';
$json_string = preg_replace($regexp, "$1:$2\"$3\"$5", $json);
if ($json_string === null) {
$message = 'An error occurred when converting a json string';
trigger_error($message, E_USER_WARNING);
return $json;
}
return $json_string;
}

}

0 comments on commit 738c721

Please sign in to comment.