美文网首页
decimal 详解

decimal 详解

作者: __XY__ | 来源:发表于2018-04-27 16:39 被阅读0次

    本篇文章回答了如下问题:
    1.为什么要有decimal,解决了什么问题,为什么不用float
    2.decimal为什么就不存在不精确的问题
    3.mysql中有对应的字段吗
    4.mysql中有对应的字段吗
    5.python中decimal如何来使用
    6.python中decimal如何用特定格式展示

    1.为什么要有decimal,解决了什么问题,为什么不用float

    2.decimal为什么就不存在不精确的问题?

    • Decimal完美利用了 【通过借助整数来表示小数的方式】解决了不精确的问题。用二进制表示任何一个精准十进制整数,不管是奇数还是偶数,都是没有问题的。
    • 具体原理参照这篇文章
      没有神话,聊聊decimal的“障眼法”

    3.mysql中有对应的字段吗

    试着创建一个表

    create table t1 (a_decimal decimal(4,2));
    
    insert into t1 set a_decimal = 100;
    

    会出现如下报错
    1264, u"Out of range value for column 'a_decimal' at row 1"
    继续
    insert into t1 set a_decimal = 10;
    显示插入成功;

    mysql dbu@(none):test> select * from t1;
    
    +-----------+
    
    | a_decimal |
    
    +-----------+
    
    | 10.00  |
    
    | 99.00  |
    
    +-----------+
    
    • 说明4代表是字段长度,2代表的是小数点后的长度。

    insert into t1 set a_decimal = 10.2392323;

    insert into t1 set a_decimal = 10.2312323;

    
    +-----------+
    
    | a_decimal |
    
    +-----------+
    
    | 10.00  |
    
    | 99.00  |
    
    | 10.00  |
    
    | 10.23  |
    
    | 10.24  |
    
    +-----------+
    
    • 实验说明小数点后多出来的部分会自动四舍五入

    4.使用场景有哪些

    • 一般所有需要精确计算的场景,比如银行以及订单支付相关

    5.python中decimal如何来使用

    Decimal ( 3.14 )
    Decimal('3.140000000000000124344978758017532527446746826171875')
    

    运行上面命令可以看出来decimal和float的区别

    6.python中的decimal如何用特定格式展示

    {0:.2f}.fromat(Decimal('32.2222'))
    

    相关文章

      网友评论

          本文标题:decimal 详解

          本文链接:https://www.haomeiwen.com/subject/iqcilftx.html