SQL 舍入和截断,需要彻底解释

发布于 2024-08-08 17:09:38 字数 463 浏览 1 评论 0原文

我是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

救赎№ 2024-08-15 17:09:38

数据的格式化应该在进行查询的脚本中完成,而不是在查询本身中完成。例如,在 PHP 中,您可以使用 sprintf< 编写以下内容/a>:(

$formatted_price = sprintf("%01.2f", $unformatted_price);

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:

$formatted_price = sprintf("%01.2f", $unformatted_price);

(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.

缘字诀 2024-08-15 17:09:38

MySQL 有一个 ROUND() 函数。

因此,只需在 SQL 查询中舍入平均值即可:

$result = mysql_query("SELECT ROUND(AVG(price),2) FROM milk WHERE price > 0 ");

如果最终遇到格式问题,可以使用 PHP 的 number_format()< /a> 输出期间的功能。

MySQL has a ROUND() function.

So just round your average in your SQL query:

$result = mysql_query("SELECT ROUND(AVG(price),2) FROM milk WHERE price > 0 ");

If you end up with formatting issues, you can use PHP's number_format() function during output.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文