I would like to remove trailing zero's according to the following rules:
Examples:
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?
Use the str. rstrip() method to remove the trailing zeros. The result won't contain trailing zeros.
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.
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..
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With