首页 > 解决方案 > 将一个字符串乘以一个整数

问题描述

我需要在 PHP 中显示一个分数。为此,我写道:

$a = 3;

$b = 2;

$c = "$a/$b";

回声 $c; // 这显示 3/2 但另一方面我想将 $c 乘以一个整数;

回声 $c * 2; // 这向我显示了一个错误

这就是向我展示的内容:(!)注意:遇到格式不正确的数值

有人能帮助我吗?

标签: php

解决方案


  • 删除操作()周围的双引号,$a/$b因为这意味着它是一个字符串而不是整数或浮点数

    $a = 3;
    $b = 2;
    $c = $a/$b; 
    echo $c * 2;
    
  • 显示分数是另一个故事

也许看看这个 PHP 将小数转换为小数并返回?

  • 或使用此功能

    function decimalToFraction($decimal){
    
        if ($decimal < 0 || !is_numeric($decimal)) {
            // Negative digits need to be passed in as positive numbers
            // and prefixed as negative once the response is imploded.
            return false;
        }
        if ($decimal == 0) {
            return [0, 0];
        }
    
        $tolerance = 1.e-4;
    
        $numerator = 1;
        $h2 = 0;
        $denominator = 0;
        $k2 = 1;
        $b = 1 / $decimal;
        do {
            $b = 1 / $b;
            $a = floor($b);
            $aux = $numerator;
            $numerator = $a * $numerator + $h2;
            $h2 = $aux;
            $aux = $denominator;
            $denominator = $a * $denominator + $k2;
            $k2 = $aux;
            $b = $b - $a;
        } while (abs($decimal - $numerator / $denominator) > $decimal * $tolerance);
    
        return [
            $numerator,
            $denominator
        ];
    }
    

来源https://www.designbyaturtle.co.uk/converting-a-decimal-to-a-fraction-in-php/


推荐阅读