SQL 舍入和截断,需要彻底解释
我是 SQL 和 PHP 方面的新手,我正在尝试对平均价格结果进行四舍五入并去掉当前出现的额外零。
目前我的结果显示为: $3.005000
我的代码当前如下所示:
$result = mysql_query("SELECT AVG(price) FROM milk WHERE price > 0 ");
$row = mysql_fetch_row ($result);
我找到了几个 SQL 舍入和截断的示例,但不幸的是,我看到的教程没有为我提供有关在何处或如何实现这些更改的有用信息。
这让我猜测在哪里进行更改——到目前为止,这些都还没有成功(显然)。
如果有人可以为我提供一个如何舍入和截断结果的示例,其中包括我需要在当前配置中进行这些更改的具体位置,那将是非常有帮助的,我将非常感激!如果我的笨拙让解释解决方案变得更加困难,我真的很抱歉。
谢谢!
I'm a novice when it comes to SQL and PHP, and I'm trying to round an average price result and take off the extra zeroes that currently appear.
Currently my result turns up as: $3.005000
My code currently reads as follows:
$result = mysql_query("SELECT AVG(price) FROM milk WHERE price > 0 ");
$row = mysql_fetch_row ($result);
I have found several examples of SQL rounding and truncation but unfortunately the tutorials I've seen provide me with no useful information on where or how I am supposed to implement these changes.
This leaves me making guesses on where to make changes -- none of which have worked out so far (obviously).
If someone could provide me with an example of how to round and truncate my results, which includes where exactly I need to make these changes in my current configuration, that would be most helpful and I would be very thankful! I'm really sorry if my n00bishness makes it more difficult to explain the solution.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
数据的格式化应该在进行查询的脚本中完成,而不是在查询本身中完成。例如,在 PHP 中,您可以使用
sprintf
< 编写以下内容/a>:(PHP 手册的示例补充)。
此外,通常价格值存储为十进制类型或缩放整数,而不是浮点类型,因为浮点值不精确。
Formatting of the data should be done in the script making the query, not in the query itself. For example, in PHP you can write the following using
sprintf
:(Example complements of the PHP manual).
Also, generally, price values are stored as
decimal
types or scaled integers, not floating-point types, since floating-point values are not exact.MySQL 有一个 ROUND() 函数。
因此,只需在 SQL 查询中舍入平均值即可:
如果最终遇到格式问题,可以使用 PHP 的 number_format()< /a> 输出期间的功能。
MySQL has a ROUND() function.
So just round your average in your SQL query:
If you end up with formatting issues, you can use PHP's number_format() function during output.