【问题标题】:Laravel input field number_format()Laravel 输入字段 number_format()
【发布时间】:2023-03-31 15:43:01
【问题描述】:

为了更好地阅读,我正在与我的用户争论输入字段中的大数字。有没有一种简单的方法可以在 1'450'000.00 等输入字段中设置格式化数字以及如何将值保存为数字?

在我这样处理的那一刻:

<input id="wbw" type="numeric" class="form-control @error('wbw') is-invalid @enderror" name="wbw" value="{{number_format( old('wbw', $bw->wbw), 2, '.', '')}}" autofocus>

但我喜欢这样的数字格式:

value="{{number_format( old('wbw', $bw->wbw), 2, '.', '´')}}"

但是我在保存时遇到了问题,因为它不再是数字了。我必须在控制器的保存功能中处理它还是在刀片中有一种优雅的方式?

感谢您的帮助!

【问题讨论】:

    标签: laravel input save number-formatting


    【解决方案1】:

    由于数字格式只需要在客户端(在浏览器中显示给用户),那么最好只使用javascript库而不是服务器端php。

    AutoNumeric.js 示例:

    window.myinput = new AutoNumeric('#myinput', 1450000);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/autonumeric@4.1.0"></script>
    <input type="text" id="myinput">
    <button onclick="alert(window.myinput.rawValue)">see value</button>

    cleave.js 示例

    window.cleave = new Cleave('.input-element', {
        numeral: true,
        numeralThousandsGroupStyle: 'thousand'
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/cleave.js/1.6.0/cleave.min.js"></script>
    <input type="text" class="input-element" value="1450000">
    <button onclick="alert(window.cleave.getRawValue())">see value</button>

    但您还必须在提交之前添加 js 事件处理程序,以便表单中的 POST 值是输入的原始值而不是格式化值

    免责声明:我与上述库的作者无关

    【讨论】:

      【解决方案2】:

      当您将使用number_format 函数时,这将产生一个字符串。因此,要保存此字符串,您需要将数据库列类型更改为 varchar 或任何其他字符串类型。

      【讨论】:

      • 由于我也使用这些值进行计算,因此我无法将它们转换为字符串......但你是对的。现在我通过在保存之前用“”替换“'”解决了这个问题。感谢您的宝贵时间!
      猜你喜欢
      • 2015-06-26
      • 2017-11-09
      • 2015-04-29
      • 2021-05-18
      • 1970-01-01
      • 2021-08-13
      • 2015-03-14
      • 2016-01-20
      • 2015-01-24
      相关资源
      最近更新 更多