zzzkkk
V2EX  ›  PHP

symfony form money type 为什么存到数据库 是价格乘以 100?

  •  
  •   zzzkkk · Dec 29, 2021 · 2418 views
    This topic created in 1603 days ago, the information mentioned may be changed or developed.

    symfony form money type 为什么存到数据库 是价格乘以 100 ? 是 doctrine 缘故吗?

    在数据库里的类型是 decimal(12,2)

    页面里输入 2.22 form->getData() 得到 222

    6 replies    2021-12-30 15:12:32 +08:00
    cpstar
        1
    cpstar  
       Dec 29, 2021
    难道不去数据库里看一下存的是 2.22 还是 222 么?如果是 222 ,那就是 getData 要做 cast ,如果是 2.22 ,还是 getData 做了错误的 cast 。
    getData:所以就是怪我喽ㄟ(≧◇≦)ㄏ。
    xumng123
        2
    xumng123  
       Dec 29, 2021 via iPhone   ❤️ 1
    钱不能用浮点数,必须化成整数
    fkdog
        3
    fkdog  
       Dec 29, 2021
    浮点数做运算会出误差的。
    0.3+0.3+0.3 算出来的结果是 0.89999999999.
    强行四舍五入精度不够的话,容易产生误差,假设一笔误差 0.00001 ,一天上百万笔交易金额产生的误差就会以千万为单位。。一年下来就是好几百万了。
    lap510200
        4
    lap510200  
       Dec 29, 2021
    @xumng123 数据库字段用的 decimal(12,2 )可以存浮点数,计算用高精计算,不一定非要存分
    TonyG
        5
    TonyG  
       Dec 29, 2021
    老派规避浮点计算问题的做法,但很有效
    zzzkkk
        6
    zzzkkk  
    OP
       Dec 30, 2021
    @fkdog

    特地去数据库测试了下 原来的 order_total 是 decimal(12,2)
    新增一个字段 total decimal(12,2)
    update orders set total = order_total *100;

    结果 sum 两个字段出来正好一样 无非是总数*100
    +------------------+
    | SUM(order_total) |
    +------------------+
    | 48461619.87020 |
    +------------------+

    +---------------+
    | SUM(total) |
    +---------------+
    | 4846161987.02 |
    +---------------+


    259585 行数据
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2431 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 16:04 · PVG 00:04 · LAX 09:04 · JFK 12:04
    ♥ Do have faith in what you're doing.