SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Evangelist
    Join Date
    Mar 2011
    Location
    Bellingham, WA
    Posts
    450
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    Fractions and Decimals

    Hello,

    Is there a javascript function that converts fractions to decimals? In other words, if a user enters (1/2) ConvertToDecimal(1/2) will spit out .5. I could definitely write a function to do this (search for "/"...if it exists, spit out stuff before "/" divided by stuff after "/" assuming that the stuff after isn't 0)....but as a newcomer to Javascript, it would be nice to know if such a function is already part of Javascript.

    Thanks so much!

    -Eric

  2. #2
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    1/2 returns 0.5

    (number).toFixed(n) returns the number formatted to a string with n decimal places

    (1/2).toFixed(1) returns '0.5'

    To remove the zero you'll need to use string.replace()-

    (1/2).toFixed(1).replace(/^0/,'');
    // returns '.5'

  3. #3
    SitePoint Evangelist
    Join Date
    Mar 2011
    Location
    Bellingham, WA
    Posts
    450
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Thanks so much. I knew that there had to be something available...

    -Eric


Tags for this Thread

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
  •