【问题标题】:PHP generate cent value of entered amountPHP生成输入金额的分值
【发布时间】:2016-03-10 18:52:38
【问题描述】:

在我的数据库中,我以美分存储用户数量。 现在我需要将用户输入转换为整数。

用户输入(字符串):|输出(整数): 1.00 100 1 100 1,51 151

我不知道如何解决这个问题。格式化金额,如:1.00 和 1,00 不是一个大问题,但是将像“1”这样的金额格式化为适当的美分数量的最佳方法是什么? 我目前使用的(不能使用像“1”这样的输入):

       $value = intval(str_replace([',','.'],'', $request->amount));

【问题讨论】:

标签: php formatting int


【解决方案1】:

转换为浮点数并乘以 100 怎么样?

<?php

header("Content-type: text/plain");

$x = '1,51';
$x = (float) str_replace(',','.', $x);
echo (int) ($x * 100)."\n";

$x = '1';
$x = (float) str_replace(',','.', $x);
echo (int) ($x * 100)."\n";

$x = '1.51';
$x = (float) str_replace(',','.', $x);
echo (int) ($x * 100)."\n";

$x = '1,00';
$x = (float) str_replace(',','.', $x);
echo (int) ($x * 100)."\n";

$x = '1.00';
$x = (float) str_replace(',','.', $x);
echo (int) ($x * 100)."\n";

返回:

151
100
151
100
100

【讨论】:

  • 我正在为每个“输入变化”寻找一种没有“过滤/切换”的方法。认为你理解我的需要。
  • 您将必须捕获所有这些逗号并替换为“。”所以它们可以被读取为小数。
  • 是的,如果存在逗号,则尝试 str_replace 将替换逗号,否则不执行任何操作。
【解决方案2】:

str_replace 应该与两个数组或两个字符串一起使用

       $value = intval(str_replace([',','.'],['',''], $request->amount));

【讨论】:

    猜你喜欢
    • 2016-06-02
    • 1970-01-01
    • 1970-01-01
    • 2018-08-30
    • 1970-01-01
    • 2021-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多