2

I have script that identifies with preg_match_all some numbers from a given file and in a given format '#(\d\,\d\d\d\d)#' (decimal, with 4 decimals). With them, later, I need to do some math operations to find out the sum, average etc.

With print_r I can see all matches from the array and it is ok (4,3456, 4,9098, etc.). I verify the type of variables and gettype() returned string

Unfortunately I cannot do math operations with them because when I use the variables in a math expression the result is always rounded regardless of what came afer the comma.

For example:

4,3456 + 4,9098 + 4,3456 = 12, or 12,0000 -- if I use number_format.

I used . instead of , in the numbers, I formatted the results with number_format, but have had no success. It seems I am missing something.

Thanks for help!

amphetamachine
  • 27,620
  • 12
  • 60
  • 72
user927495
  • 73
  • 1
  • 1
  • 4

2 Answers2

0

PHP uses the . character as decimal separator, so you have to replace the , by a . in your matched numbers before converting them to numbers:

$number = floatval(strtr("1,234", ",", "."));
// 1.234

Example:

<?php

$numbers = array("1,234", "5,67");
$numbers = str_replace(",", ".", $numbers);
echo number_format($numbers[0] + $numbers[1], 4, ',', ' ');

Try it here: http://codepad.org/LeeTiKPF

Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194
0

The error happens even before the number_format call -- PHP considers . as the decimal separator, not ,. you need to str_replace all your array elements:

$values_array = str_replace(",", ".", $values_array)
Joaquim Rendeiro
  • 1,388
  • 8
  • 13