Convert Fraction String to Decimal?

前端 未结 16 639
谎友^
谎友^ 2020-12-05 13:55

I\'m trying to create a javascript function that can take a fraction input string such as \'3/2\' and convert it to decimal—either as a string \'1.5\'

16条回答
  •  遥遥无期
    2020-12-05 14:34

    I have a function I use to handle integers, mixed fractions (including unicode vulgar fraction characters), and decimals. Probably needs some polishing but it works for my purpose (recipe ingredient list parsing).

    • NPM
    • GitHub

    Inputs "2 1/2", "2½", "2 ½", and "2.5" will all return 2.5. Examples:

    var numQty = require("numeric-quantity");
    
    numQty("1 1/4") === 1.25;  // true
    numQty("3 / 4") === 0.75;  // true
    numQty("¼" ) === 0.25;     // true
    numQty("2½") === 2.5;      // true
    numQty("¾") === 0.75;      // true
    numQty("⅓") === 0.333;     // true
    numQty("⅔") === 0.667;     // true
    

    One thing it doesn't handle is decimals within the fraction, e.g. "2.5 / 5".

提交回复
热议问题