php - 将一个字符串乘以一个整数
问题描述
我需要在 PHP 中显示一个分数。为此,我写道:
$a = 3;
$b = 2;
$c = "$a/$b";
回声 $c; // 这显示 3/2 但另一方面我想将 $c 乘以一个整数;
回声 $c * 2; // 这向我显示了一个错误
这就是向我展示的内容:(!)注意:遇到格式不正确的数值
有人能帮助我吗?
解决方案
删除操作()周围的双引号,
$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/
推荐阅读
- python - 如何在给定条件下填充列以检查索引列表并在给定索引的情况下分配
- python - 我想使用python替换字符串中交替出现的子字符串
- javascript - 有没有办法在 React 中为装饰器创建组合函数?
- can-bus - CAN 总线关闭状态信息
- javascript - 使用 Protractor webdriver 在单独的框架中打开 url
- javascript - 解析对象内部的 JSON 字符串
- eslint - Linter sort-imports - 导入应按字母顺序排序
- solidity - 如何正确使用 ECDSA.sol 模块?
- bazel-rules - Bazel/sandboxfs/ld.gold:中断链接步骤时损坏的二进制文件
- javascript - 缩放 SVG 路径的填充部分