首页 > 解决方案 > 将分数转换为小数

问题描述

我有带有 HTML 分数的字符串。如何将它们转换为小数?我需要用它们的值替换分数吗?但是在 1 ⅔ 的情况下就不是那么容易了,因为我需要加上 1。

<?php

$mappingArr = [
  '½' => 1/2,
  '⅓' => 1/3,
  '⅔' => 2/3,
  '¼' => 1/4,
  '¾' => 3/4,
  '⅕' => 1/5,
  '⅖' => 2/5,
  '⅗' => 3/5,
  '⅘' => 4/5,
  '⅙' => 1/6,
  '⅚' => 5/6,
  '⅐' => 1/7,
  '⅛' => 1/8,
  '⅜' => 3/8,
  '⅝' => 5/8,
  '⅞' => 7/8,
  '⅑' => 1/9,
  '⅒' => 1/10
];

$fractionString1 = "⅓ Test something else";
$fractionString2 = "1½ Test (test)";
$fractionString3 = "1 ⅔ Test, test";

// how to convert HTML vulgar fractions to decimals?

// result should be
$fractionStringDecimal1 = "0.33 Test something else";
$fractionStringDecimal2 = "1.5 Test (test)";
$fractionStringDecimal3 = "1.67 Test, test";
?>

标签: phphtml-entities

解决方案


一种方法是遍历每个字符并检查它是否是数字或分数字符。

代码可能类似于以下内容。我正在使用 unicode 字符串操作(mb_substr 和 mb_strlen),因为分数字符是 uncode 字符。

function convertFractionToDecimals($str){
    $result = "";
    $number = null;
    
    //iterate over each unicode char in the string
    for($i = 0; $i < mb_strlen($str); $i++){
        //if current char is a number, save it temporarly
        if(is_numeric(mb_substr($str, $i, 1))){
            if($number == null){
                $number = mb_substr($str, $i, 1);
            } else {
                $number .= mb_substr($str, $i, 1);
            }
            continue;
        }
           
        //if the current char is a fraction char, resolve it
        if(isFraction(mb_substr($str, $i, 1))){
           if($number != null){
               $result .= $number + resolveFraction(mb_substr($str, $i, 1));
           } else {
               $result .= resolveFraction(mb_substr($str, $i, 1));
           }
            
           continue;
        }
        
        //if we have a number in front of the current char, that is a space, check if next char is a space or a fraction
        if($number != null && mb_substr($str, $i, 1) === ' ' && $i + 1 < mb_strlen($str) && (mb_substr($str, $i+1, 1) === ' ' || isFraction(mb_substr($str, $i+1, 1)))){
           continue;
        }
           
        if($number != null){
            $result .= $number;
            $number = null;
        }
           
        //a char, that is not a number nor a fraction will be just added to result
        $result .= mb_substr($str, $i, 1);
    }
    
    
    return $result;
}

function getFractionMap(){
    return $mappingArr = [
      '½' => 1/2,
      '⅓' => 1/3,
      '⅔' => 2/3,
      '¼' => 1/4,
      '¾' => 3/4,
      '⅕' => 1/5,
      '⅖' => 2/5,
      '⅗' => 3/5,
      '⅘' => 4/5,
      '⅙' => 1/6,
      '⅚' => 5/6,
      '⅐' => 1/7,
      '⅛' => 1/8,
      '⅜' => 3/8,
      '⅝' => 5/8,
      '⅞' => 7/8,
      '⅑' => 1/9,
      '⅒' => 1/10
    ];
}
           
function isFraction($char) {
   return array_key_exists($char, getFractionMap());    
}
           
function resolveFraction($char){
    return getFractionMap()[$char];       
}

推荐阅读