Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Removing trailing zeros from a float up to and including the '.' 1

Status
Not open for further replies.

bengR

Technical User
Oct 30, 2007
13
US
I am using Active Perl 5.8.8.
I am trying to remove trailing zeros from floating point numbers.
I also want to remove the decimal point if there is no decimal component.
eg
[ul]
[li]1.100 => 1.1[/li]
[li]2.020 => 2.02[/li]
[li]3.003 => 3.003[/li]
[li]4.000 => 4[/li]
[/ul]

This is what I have:
Code:
{
   no warnings 'uninitialized';
   $_ =~ s/^(\d+\.0*[1-9]+)0*$|^(\d+)\.0+$/$1$2/;
}

This snippet works fine, but I was wondering if there was a better, more elegant way to do this that did not require multiple capture buffers.
(something like perl 5.10s (?|pattern)).
Thank you for your time.
 
I think you want sprintf but I'm not sure which options.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[noevil]
Travis - Those who say it cannot be done are usually interrupted by someone else doing it; Give the wrong symptoms, get the wrong solutions;
 
Thanks prex1.
That works great, even on BigFloat numbers.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top