Jump to content

trim characters in a string after a certain character?


misterm

Recommended Posts

Hi

 

I am trying to trim the last 2 chracters of a sting that follow "."

So for example  45.4545 will become 45.45.

I need this to work too if the string starts with any number of characters before the ".". eg 4.4545 or 445.4545

 

I tried using

$myString = substr ($myString, 0,-2);

which will give me 45.45 but which will not work if my string has only 1 character before the "." (which would give 5.454).

 

to recap:

I only want 2 characters to appear after the "." no matter how many characters appear before the ".".

 

 

Any help would be much appreciated  :)

 

Many thanks

 

D

 

 

 

So If I have a string containing 44.4567 I want to trim to just 44.45, which I can do with

But this won't work if my string is 4.4567

 

But what I need to do really is trim whatever appeas after the "." by 2 characters so if my string is just

$newstring = end(explode('.', $myString));
$mycorrectnewstring = substr ($newstring, 0,-2);

 

OR

 

$newstring = explode('.', $myString);
$mycorrectnewstring = substr ($newstring[1], 0,-2);
$collective = "$newstring[0].$mycorrectnewstring";
//collective prints 44.45

 

Thanks inversesoft123

 

The second option you posted works great when $myString has 2 characters before the ".", but when there is only 1, it still shows 3 chcaracters after the ".":

 

so

a string with the value of 17.4942 is displayed as 17.49

But when it it's value is 7.4942, it is displayed as 7.494 and not 7.49  :/

 

Thanks again

 

D

 

 

 

replace -2 with 2

 

$newstring = explode('.', $myString);

$mycorrectnewstring = substr ($newstring[1], 0,2);

$collective = "$newstring[0].$mycorrectnewstring";

//collective prints 44.45

 

As you want first 2 number after decimal. then you have to trim string from starting part.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.