3

I have an issue with some json code where decimal numbers MUST be encoded without quotes and maintain two decimal places

e.g.

{12.34, 33.40, 25.00}

My problem is that the array I have creates the numbers as string

foreach($numbers as $n)
{
  $result[] = number_format($n, 2, '.', '');
}
json_encode($result);

// result = {"12.34", "33.40", "25.00"}
7
  • 3
    I don't think you can get a value like 33.40 or 25.00 as anything but a string... ie the reason number_format always returns a string Commented Jun 21, 2014 at 23:02
  • Mark M, try var_dump(33.40); it returns float type Commented Jun 21, 2014 at 23:04
  • 1
    Yes, it is a float type - but the resulting value is 33.4 not 33.40. You would get the same result for 33.4000 or 33.4000000 - all will strip off the unnecessary 0s and return 33.4 Commented Jun 21, 2014 at 23:07
  • 1
    @MarkM is right. This is not possible in PHP. Do echo 34.40;. It will display without the last zero. The same goes for var_dump. Commented Jun 21, 2014 at 23:08
  • It doesn't make much sense elsewhere either. There is a discussion on the problem here: groups.google.com/forum/#!topic/json-schema/NPIy68ZXE_k Commented Jun 21, 2014 at 23:41

4 Answers 4

2

I had similar issie with this. This may not be the best code but it work for me. Maybe it can help you. Try this (I am using codeigniter):

function getData() {

    $data = $this->Teplomer_model->showData(); //get your data from database as return $query->result();

    //create array
    $arr = array();

    //foreach data to array
    foreach ($data as $row) {
        $arr[] = array(
        "id"                =>  $row->id_teplota,
        "datum"             =>  $row->cas_teplota,
        "teplota"           =>  $row->teplota_teplota,
        "vlhkost"           =>  $row->vlhkost_teplota
        );
    }

    //echo array as json and check if there is any numbers
    echo json_encode($arr, JSON_NUMERIC_CHECK );
}

And output:

{"id":3,"datum":"2019-02-08 14:03:31","teplota":22.33,"vlhkost":19.7},{"id":4,"datum":"2019-02-08 14:18:35","teplota":23,"vlhkost":19}
Sign up to request clarification or add additional context in comments.

1 Comment

This is perfect unless you need some numeric values as strings. Be careful. Maybe you don't want "00000123" to become 123 or VAT code or social security number or to shorten. In my town phone numbers begin with "02" and you want to keep that zero. In that case you have to build the JSON manually (as jordan121sa's reply)
2

You could do:

$result[] = (float) number_format($n, 2, '.', '');

Result:

[12.42,33.4,25]

5 Comments

Same thing as I have just replied to Marcel Gwerder above. Forcing the variable to float type defeats the purpose of number_format
What you want is impossible. It is not valid JSON to drop the quotes without the type being either int, float or double. It is simply not possible. Also, you said nothing about your problem in the initial question, so we have in fact solved what you asked us.
In fact what I want is for the type to be float. Also edited initial question to specify that number must have two decimal places
@Martin : What my code does is simply to cast the string to a float, so what you are saying is that my code is correct. According to your comments, what you want is not for the type to be float. You want something that does not exist.
Converting to string then to float in nonsense. To truncate decimals use round()
2

You can use floatval():

$result[] = floatval(number_format($n, 2, '.', ''));

3 Comments

I have tried that, but it defeats the purpose of having number_format as I always need the two decimal digits e.g. number_format(1, 2, '.', '') // returns 1.00 floatval(number_format(1, 2, '.', '')) // returns 1
Then you wont be able to convert it to a float, because the .00 is irrelevant. You'll have to keep the string I guess...
Converting to string then to float in nonsense. To truncate decimals use round()
1

Came across a similar problem. The only way to achieve this is to build the raw json object rather than using json_encode.

$jsonStr = '{';
$lastElement = count($numbers);
$i = 1;
foreach($numbers as $n)
{
  $jsonStr .= number_format($n, 2, '.', '');
  if($i != $lastElement){
     $jsonStr .= ',';
  }
  $i++;
}
$jsonStr .= '}';
echo $jsonStr;

I know it's not the nicest way to code, but it's the only way to keep decimal points in a json object.

1 Comment

This is the only way if you want to keep some numeric values as string (VAT code, phone?) and others as numbers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.