1

I have an array that has random integer numbers and I want to convert them into float numbers but I want to put decimal point after first two digits only. Following is my array:

[143] => Array
    (
        [0] => 723579
        [1] => 112338261
    )

[144] => Array
    (
        [0] => 723575
        [1] => 11233847
    )

[145] => Array
    (
        [0] => 723575
        [1] => 11233
    )

And I want the output to be the following.

[143] => Array
    (
        [0] => 72.3579
        [1] => 11.2338261
    )

[144] => Array
    (
        [0] => 72.3575
        [1] => 11.233847
    )

[145] => Array
    (
        [0] => 72.3575
        [1] => 11.233
    )

I think that I can manipulate it through string modification first and convert it into float number. Is there any easiest or simple way to manipulate it in PHP?

4
  • The numbers in your result are floats, not int. Commented Oct 1, 2020 at 5:08
  • You seem to misunderstand what a "round number" is. Your input contains round numbers, the output contains fractions. Commented Oct 1, 2020 at 5:09
  • i dont realy understand the correct name of the number format in english. but is there any way to manipulate the array to those format? Commented Oct 1, 2020 at 5:13
  • Yes there is. I put it in my answer below. Commented Oct 1, 2020 at 5:15

1 Answer 1

1

Use nested foreach loops. Use reference variables so you can modify the original arrays. Insert a . after the second digit, then convert that to a float.

foreach ($array as &$nested_array) {
    foreach ($nested_array as &$val) {
        $val = floatval(substr($val, 0, 2) . "." . substr($val, 2));
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

i think i need to read more about format number in english, thanks a lot

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.