将小数点替换为浮点值中的运算符并输出结果..php


Replacing decimal point with an operator in a float value and output the result. php

我这里有一个奇怪的问题。我该怎么做。所以我有一个十进制数 1.2;我想用加号替换小数点,这样它就是 1+2 并输出值 3。

这就是我到目前为止尝试过的。使用str_replace替换点

<?php
    $a = 1.2; 
    $added_decimal = str_replace('.','+',$a);
    echo $added_decimal; 

上面的代码输出 1+2,因此它不会计算它。

我还尝试将小数转换为这样的数组;

<?php
$a = 1 .'.'. 2; //Concatenated it
explode('.',$a); //entered the delimeter
echo $a[0] + $a[2]; //this outputs 3;

所以这个工作正常,但问题是当$a1.20时。如果我上面的代码被使用,这也将输出 3。我将如何获得 1+ 20 并输出 21?

你的第二个代码片段几乎是正确的。你只需要将 explode() 结果存储在一个变量中。请参阅此代码片段:

<?php
$a = 1 .'.'. 20; //Concatenated it
$x = explode('.',$a); //entered the delimeter
echo $x[0] + $x[1]; //this outputs 21;

当你执行 $a[0] 时,你实际上是访问字符串的索引,而不是 explode() 结果。