更改PHP中数字的符号? [英] Changing the sign of a number in PHP?

查看:69
本文介绍了更改PHP中数字的符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个花车:

-4.50
+6.25
-8.00
-1.75

如何将所有这些都更改为负浮点数,以便变为:

How can I change all these to negative floats so they become:

-4.50
-6.25
-8.00
-1.75

我还需要一种相反的方法

Also I need a way to do the reverse

如果浮点为负,则使其为正.

If the float is a negative, make it a positive.

推荐答案

琐碎

$num = $num <= 0 ? $num : -$num ;

或者更好的解决方案,恕我直言:

or, the better solution, IMHO:

$num = -1 * abs($num)

如@VegardLarsen所发布的,

As @VegardLarsen has posted,

可以避免显式乘法的简短性,但我更喜欢可读性而不是简短性

the explicit multiplication can be avoided for shortness but I prefer readability over shortness

我建议避免使用if/else(或等效的三元运算符),尤其是当您必须操纵多个项目(循环或使用 lambda函数)时,这会影响性能.

I suggest to avoid if/else (or equivalent ternary operator) especially if you have to manipulate a number of items (in a loop or using a lambda function), as it will affect performance.

如果浮点为负,则使其为正."

要更改数字的符号,您只需执行以下操作:

In order to change the sign of a number you can simply do:

$num = 0 - $num;

,或者乘以-1,当然:)

or, multiply it by -1, of course :)

这篇关于更改PHP中数字的符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆