removing trailing zeros from decimal

Posted on 2005-04-07
Last Modified: 2008-01-09
i am dealing with very small nubers up to 8 decimal places in some, bt some are only 3 decimals and i need to show them all.

What is the easiest way to remove the trailing zeros for some numbers
i.e. 0.00456000 becomes 0.00456 but if the number is 0.04567890 it becomes 0.0456789 i do not want to round off just remove zeros from the end

 I am using

printf("%0.8f", $total_base);

to format the numbers from my equations other wise they come scientific


thanks in advance for any and all help
Question by:mrwilde
    LVL 4

    Expert Comment

    Hi mrwilde,

    one way this can be done is
    for ($i = 0; $i < 8; $i++)
        if (round($total_base,$i) == $total_base)
            printf("%0." . $i . "f", $total_base);

    LVL 6

    Expert Comment

    Watch this :)

    function rtrim_zeros ($num) { return rtrim (sprintf("%0.8f", $num), "0"); }
    LVL 6

    Accepted Solution


       $total_base = 0.004560000;
       echo rtrim_zeros ($total_base);
       echo "<br>";

       $total_base = 0.04567890;
       echo rtrim_zeros ($total_base);
       echo "<br>";

       function rtrim_zeros ($num) { return rtrim (sprintf("%0.8f", $num), "0"); }


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    The Client Need Led Us to RSS I recently had an investment company ask me how they might notify their constituents about their newsworthy publications.  Probably you would think "Facebook" or "Twitter" but this is an interesting client.  Their cons…
    Consider the following scenario: You are working on a website and make something great - something that lets the server work with information submitted by your users. This could be anything, from a simple guestbook to a e-Money solution. But what…
    The viewer will learn how to count occurrences of each item in an array.
    This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

    737 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    20 Experts available now in Live!

    Get 1:1 Help Now