【发布时间】:2012-06-20 05:22:01
【问题描述】:
我需要知道如何服用
10.25 转成 1025
基本上它需要从任何数字中删除句号,例如 1500.25 应该是 150025
【问题讨论】:
-
1500.25是浮点数还是字符串?
我需要知道如何服用
10.25 转成 1025
基本上它需要从任何数字中删除句号,例如 1500.25 应该是 150025
【问题讨论】:
1500.25 是浮点数还是字符串?
$number = str_replace('.','',$number);
【讨论】:
1500.3,会发生什么?
how to take 10.25 and turn it to 1025,所以答案是使用str_replace,它会在这里工作。如果问题与问题不符,我们概不负责
10.3567 在“删除句号”时当然会变成103567。
如果货币是浮点数:乘以 100(并将结果转换为 int)。
$currency = 10.25;
$number = (int)($currency * 100); //1025
请注意,此解决方案只会保存前两位小数 - 如果您有像 10.123 这样的数字,3 将被截断而不四舍五入。
【讨论】:
浮点运算的定义并不准确。因此,如果它是一个字符串,则不要将值转换为浮点数,如果它是浮点数,则避免将其转换为字符串。
这是一个检查值类型的函数:
function toCents($value) {
// Strings with a dot is specially handled
// so they won't be converted to float
if (is_string($value) && strpos($value, '.') !== false) {
list($integer, $decimals) = explode('.', $value);
$decimals = (int) substr($decimals . '00', 0, 2);
return ((int) $integer) * 100 + $decimals;
// float values are rounded to avoid errors when a value
// like ".10" is saved as ".099"
} elseif (is_float($value) {
return round($value * 100);
// Other values are strings or integers, which are cast
// to int and multiplied directly.
} else {
return ((int) $value) * 100;
}
}
【讨论】:
如果您只想替换一个字符,请使用 strtr 代替 str_replace
$number = str_replace('.','',$number);
和
$number = strtr($number, array('.', ''));
输出相同,但 strtr 更好。
【讨论】: