Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove trailing zeros from a string

Tags:

php

I would like to remove trailing zero's according to the following rules:

  • The input number will always have 4 decimal places
  • The output number should always have between 2 and 4 decimals
  • If the last two digits after the decimal is a zero, then remove both of them
  • If the last digit after the decimal is a zero, then remove it

Examples:

  • 1.0000 -> 1.00
  • 1.4000 -> 1.40
  • 1.4100 -> 1.41
  • 1.4130 -> 1.413
  • 1.4136 -> 1.4136

I have considered the following:

if (substr($number, -2) == '00') return substr($number, 0, 4);
if (substr($number, -1) == '0') return substr($number, 0, 5);
return $number;

Are there any better ways of doing this?

like image 651
JonoB Avatar asked Jun 22 '13 16:06

JonoB


People also ask

How do you remove trailing zeros from a string in Python?

Use the str. rstrip() method to remove the trailing zeros. The result won't contain trailing zeros.

How do I get rid of trailing zeros in Java?

stripTrailingZeros() is an inbuilt method in Java that returns a BigDecimal which is numerically equal to this one but with any trailing zeros removed from the representation. So basically the function trims off the trailing zero from the BigDecimal value.

How do you trim trailing zeros in C++?

you can round-off the value to 2 digits after decimal, x = floor((x * 100) + 0.5)/100; and then print using printf to truncate any trailing zeros..

How do you remove leading and trailing zeros in Java?

Using StringBuilderdeleteCharAt() when we remove trailing zeroes because it also deletes the last few characters and it's more performant. If we don't want to return an empty String when the input contains only zeroes, the only thing we need to do is to stop the loop if there's only a single character left.


1 Answers

I think this should work:

return preg_replace('/0{1,2}$/', '', $number);

$strings = array ('1.4000', '1.4100', '1.4130', '1.4136', '1.4001', '1.0041');
foreach ($strings as $number) {
  echo "$number -> " . preg_replace('/0{0,2}$/', '', $number) . "\n";
}

Produces:

1.4000 -> 1.40
1.4100 -> 1.41
1.4130 -> 1.413
1.4136 -> 1.4136
1.4001 -> 1.4001
1.0041 -> 1.0041
like image 132
Barmar Avatar answered Nov 03 '22 17:11

Barmar