Laravel 4和; Bootstrap 3 - 奇怪的浮动显示问题

时间:2015-02-03 15:15:09

标签: twitter-bootstrap laravel view laravel-4

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

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

迁移表时,它的外观(在navicat中):

enter image description here

我在表格中有以下数据:

enter image description here

当我在视图中显示上述数据时(使用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>

总体积呈现如下:

enter image description here

为什么总重量很好,但音量显示如此?有什么想法吗?

1 个答案:

答案 0 :(得分:0)

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扩展名。