reemplace los ceros finales regex con un punto (.) y una coma (,) incluido el delimitador,

I use this regular expression to remove trailing zeros from numbers with dot(.) delimiter:


and I'm replacing with $1.


  • 9.50
  • 2.00
  • 3.06
  • 3.000

me dará:

  • 9.5
  • 2
  • 3.06
  • 3

But it doesn't seem to work the same way with comma(,). I tried this but with no luck:


I'm new to PHP and this is my first question here. Thank you in advance.

preguntado el 09 de marzo de 12 a las 15:03

Shouldn't the '.' be escaped in ur original regexp? -

@RedBaron: the dots were escaped, but some of the backslashes weren't showing because the OP didn't use code formatting. -

2 Respuestas

If these are separate strings, numbers only, then use: [.,]?0*$ and replace it with an empty string.

respondido 09 mar '12, 15:03

Both of them worked!!These numbers are prices wich im receiving them with both delimiters ,so i have to remove them.The only problem was the percent(%) symbol which i had to remove it first. Thank you guys!! - maik72

The percent symbol was for discounts with the same format as prices. - maik72

Six characters! I came up with two solutions, one using a conditional and the other with a branch-reset group, and you solve it with a six-character regex. I am humbled. :D - Alan Moore

Sorry but we have to assume that the same string gives me numbers with both delimters like this $prices=30.00 or $prices=25,50 .The above solutions work prefectly if there is a comma but with dot a get this 60.00=6. Any suggestions? Caution:I do not have numbers like this 30.2,00 - maik72

Assuming you mean to replace the trailing zeros in decimal numbers with commas like 1,50 and not numbers using commas to group digits into triplets, then search for (\d*[.,](?:\d*[1-9]|))0*$ y reemplazarlo con $1

If the regex doesn't match your string, then there is no dot or comma present, which means there's no fractional part of the number, so you don't want to remove the trailing zeros because they are significant.

Remember that with regex, you need to escape the dot because it's a special symbol (except when between brackets), but you shouldn't escape the comma

respondido 09 mar '12, 16:03

You're assuming right these are prices which im receiving them with both delimiters(. and ,) so i have to remove the trailing zeros.And your expression is also right!!! - maik72

You' re right Karoly. Your code works for both, delimiters and traling zeros, removing them at once.The - maik72

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.