【问题标题】:Laravel 4 & Boostrap 3 - weird float display issueLaravel 4 & Bootstrap 3 - 奇怪的浮动显示问题
【发布时间】:2015-04-02 20:24:30
【问题描述】:

我的迁移类中有以下表格之一:

$table->float('total_weight');
$table->float('total_volume');

当表格被迁移时,它是这样的(在navicat中):

我在表中有以下数据:

当上述数据显示在我的视图中时(使用 Bootstrap 3):

<!-- Total Weight Field -->
<div class="form-group">
    {{ Form::label('total_weight', 'Total Weight (KG)') }}
    {{ Form::text('total_weight', $goods_in->total_weight, ['class' => 'form-control input-lg', 'disabled' => 'disabled']) }}
</div>

<!-- Total Volume Field -->
<div class="form-group">
    <label for="total_volume">Total Volume (M<sup>3</sup> / CBM)</label>
    {{ Form::text('total_volume', $goods_in->total_volume, ['class' => 'form-control input-lg', 'disabled' => 'disabled']) }}
</div>

总体积是这样渲染的:

为什么总重量很好,但体积却显示成这样?有什么想法吗?

【问题讨论】:

  • 我也有这个,id 最终将归档小数化以避免像$table-&gt;decimal('total_weight',8,2);$table-&gt;decimal('total_volume',8,2);这样的四舍五入问题

标签: twitter-bootstrap laravel view laravel-4


【解决方案1】:

在 PHP 和 MySQL 中,float 数据类型是一个近似值。有很多关于计算机科学中浮点数的文献,所以我不会详细介绍。但是,您可能至少应该查看用于 PHP 的 float documentation 和用于 MySQL 的 float documentation

基本思想是用二进制表示小数是很困难的。在您的具体情况下,发生这种情况的原因是因为 .25 可以精确表示。但是,.6 不能,所以它是一个近似值。

要亲自查看,请尝试以下代码:

// up the PHP precision to see the hidden approximations
ini_set('precision', 20);
var_export(1.25); // exact
var_export(2.6); // approximate
// another fun one
var_export(0.1 + 0.2 == 0.3); // false

因此,如果您需要存储精确值,则需要使用存储为精确值而非近似值的数据类型。对于 MySQL,您需要使用 DECIMAL 类型。如果您实际上不需要存储确切的值,但想查看确切的值,则需要在视图中进行一些舍入。此外,如果您需要对浮点值进行任何精确的数学运算,请查看 BC Math 扩展。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-19
    • 1970-01-01
    • 1970-01-01
    • 2014-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多