在 MySQL 查询中使用数字格式的最佳方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2854985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 16:04:25  来源:igfitidea点击:

What is the best way to use number format in a MySQL query?

mysql

提问by Prabhu M

I need to set the "Total Price" value to be a two decimal point value like "56.35". Now it's showing fraction values like "56.3566666". I need it to be formatted by MySQL "SELECT" query.

我需要将“总价”值设置为两个小数点值,例如“56.35”。现在它显示了像“56.3566666”这样的分数值。我需要通过 MySQL“SELECT”查询对其进行格式化。

回答by Bj?rn

select
    format(field, 2) as formatted
from
    table

Do note that Format() returns a string, and the result will be with two decimal places (in the above example) - i.e. 100 will be formatted as 100.00.

请注意 Format() 返回一个string,结果将带有两个小数位(在上面的示例中) - 即 100 将被格式化为 100.00。

Documentation.

文档

回答by MasterJeev

That works too, but if you need it for further calculations or what not AND you have MySQL > 5.0.8 you could also try:

这也有效,但如果您需要它进行进一步计算或不需要它并且您拥有 MySQL > 5.0.8,您也可以尝试:

select
    cast(field as decimal(14, 2)) as formatted
from
    table

It is a bit more flexible this way! I like flexible...

这种方式更灵活一些!我喜欢灵活...

回答by zzapper

Hi I thought I wanted FORMAT but didn't like the formatting of the whole number part (with commas)

嗨,我以为我想要 FORMAT 但不喜欢整数部分的格式(带逗号)

SELECT ROUND(11000.299, 2);

选择回合(11000.299, 2);

SELECT ROUND(11000.301, 2);

选择回合(11000.301, 2);

SELECT ROUND(11000.3, 2);

选择回合(11000.3, 2);

all three renders 11000.30

所有三个渲染 11000.30

SELECT FORMAT(11000.3, 2);

renders 11,000.3

渲染 11,000.3