dpxw7293 2018-06-21 05:35
浏览 994
已采纳

MySQL如何在使用除法时保留精度?

Let us say we have values we've retrieved in the tables, these values are strings so it's fine to divide them. We have this kind of report, but I don't like to handle it thru a Programming Language, yet to run it thru 1 sql query to retrieve all reports.

To make the query short for asking here, take a look at below simple mysql query.

select "68078004281240001301" / "1000000000000000000" from {a dummy table};

The above returns a value 68.07800428124, and we are lossing 0001301 in the decimal point.

Already tried FORMAT() or ROUND() yet not working, or I missed some mysql functions?


But when using bcmath in PHP, we could do it like this

$n = '68078004281240001301';
$d = '1000000000000000000';
bcdiv($n, $d, strlen($d) - 1);

and the value above will give us an exact precision we want 68.078004281240001301


Please remember that I am going to use this for reporting along with filters later on.

  • 写回答

1条回答 默认 最新

  • dsgdsf12312 2018-06-21 06:13
    关注

    I'm assuming the difficulty is that as your dividing two strings - which are actually integers, it doesn't know the type of values to use (as in precision). If you instead cast the values to the decimal type, you can force it to work to any precision (up to 65 digits)...

    select "68078004281240001301" / "1000000000000000000", cast("68078004281240001301" as decimal(60,30))/ cast("1000000000000000000" as decimal(60,30))
    

    gives...

    "68078004281240001301" / "1000000000000000000"
    68.07800428124
    
    cast("68078004281240001301" as decimal(60,30))/ cast("1000000000000000000" as decimal(60,30))
    68.078004281240001301000000000000
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA