3

I have an amount like 0003000, the last 2 digits are the decimal number. I want to transform 0003000 to 00030,00 (insert a decimal comma in front of the last 2 digits). I tried to do this with substring. I take the length of the string with strlen and then I make -2, but it ignores the -2.

Here is an example, why is it being ignored?

substr($this->arrCheck['amountsum'],0,(strlen($this->arrCheck['amountsum']-2)))
JJJ
  • 32,902
  • 20
  • 89
  • 102
Markey
  • 33
  • 1
  • 3

7 Answers7

2

You have the strlen close bracket after the -2. Try:

substr($this->arrCheck['amountsum'],0,(strlen($this->arrCheck['amountsum'])-2))
Sam Martin
  • 1,238
  • 10
  • 19
2

you don't need strlen() in this case, try:

substr($this->arrCheck['amountsum'], 0, -2) . ',' . substr($this->arrCheck['amountsum'], -2)
Sascha Galley
  • 15,711
  • 5
  • 37
  • 51
2

It's because your -2 is in the strlen function instead of outside it:

strlen($this->arrCheck['amountsum']-2)

Should be:

strlen($this->arrCheck['amountsum'])-2

But all in all you don't need to use strlen, since substr accepts a negative number as number of characters before the end of the string: PHP Manual

So your whole code above can be replace by:

substr($this->arrCheck['amountsum'], 0, -2)

And the whole thing can be achieved by:

substr($this->arrCheck['amountsum'], 0, -2).','.substr($this->arrCheck['amountsum'], -2)
Paul
  • 139,544
  • 27
  • 275
  • 264
2

You can also do the folowing:

echo substr_replace("0003000", ",", -2, 0); // output: 00030,00

echo number_format("0003000" / 100, 2, ',', ''); // output: 30,00
Benjamin Crouzier
  • 40,265
  • 44
  • 171
  • 236
1

use number_format() instead. That will be easy to use.

http://www.w3schools.com/php/func_string_number_format.asp

user909058
  • 188
  • 1
  • 2
  • 11
0

You can use number_format

http://php.net/manual/en/function.number-format.php

or correct your code.

substr($this->arrCheck['amountsum'],0,(strlen($this->arrCheck['amountsum']) -2))

you can't place -2 into strlen() function

genesis
  • 50,477
  • 20
  • 96
  • 125
0

this way ?

substr($this->arrCheck['amountsum'], 0, -2).','.substr($this->arrCheck['amountsum'], -2);
Mihai Iorga
  • 39,330
  • 16
  • 106
  • 107