SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Enthusiast
    Join Date
    Apr 2012
    Posts
    70
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Converting a percents or fractions to decimal from a variable

    Anyone know an easy way to take a percent/fraction variable and convert it to a decimal number? I won't know which it will be.



    PHP Code:
    $Fraction '3/16';
    $Percent '25%';


    $Convert = ?; // .125 

  2. #2
    Programming Team silver trophybronze trophy
    Mittineague's Avatar
    Join Date
    Jul 2005
    Location
    West Springfield, Massachusetts
    Posts
    17,264
    Mentioned
    196 Post(s)
    Tagged
    2 Thread(s)
    There is no "fraction" datatype.

    But it's only simple division in both cases

    fraction -> float would be numerator divided by denominator

    and per cent (per 100) -> float would be number divided by 100

    Are your variables strings?

  3. #3
    SitePoint Enthusiast
    Join Date
    Apr 2012
    Posts
    70
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yeah they are strings. I guess the only way would be to match to see if it's a percent or fraction, then process it?

  4. #4
    Programming Team silver trophybronze trophy
    Mittineague's Avatar
    Join Date
    Jul 2005
    Location
    West Springfield, Massachusetts
    Posts
    17,264
    Mentioned
    196 Post(s)
    Tagged
    2 Thread(s)
    Ideally it would be better to have more control over the input so you know what they are and don't need extra processing. Different form inputs?

    Otherwise you need to figure out what is what from the possible sting formats.

    If the "fraction" will always have "/" and the "per cent" will always have "%" then I guess that would be easy enough.

    You can split() the fraction string on the "/", cast to numeric and divide $piece[0] by $piece[1]

    You could replace() the "%" with nothing to get rid of it, cast to numeric and divide by 100

  5. #5
    SitePoint Addict kduv's Avatar
    Join Date
    May 2012
    Location
    Atlanta, GA
    Posts
    244
    Mentioned
    5 Post(s)
    Tagged
    0 Thread(s)
    As PHP is a dynamically typed language, you "usually" won't need to cast the string to an int as PHP will do that for you.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •