SQL SQLite 格式编号始终保留 2 个小数位

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9149063/
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-09-01 14:15:17  来源:igfitidea点击:

SQLite format number with 2 decimal places always

sqlsqlite

提问by aleroot

I have some tables in a SQLite database that contains FLOAT column type, now i want to retrieve the value with a Query and format the float field always with 2 decimal places, so far i have written i query like this one :

我在包含 FLOAT 列类型的 SQLite 数据库中有一些表,现在我想用查询检索值并将浮点字段的格式设置为始终带有 2 个小数位,到目前为止,我已经编写了这样的查询:

SELECT ROUND(floatField,2) AD field FROM table

this return a resultset like the the following :

这将返回如下所示的结果集:

3.56
----
2.4
----
4.78
----
3

I want to format the result always with two decimal places, so :

我想总是用两位小数来格式化结果,所以:

3.56
----
2.40
----
4.78
----
3.00

Is it possible to format always with 2 decimal places directly from the SQL Query ? How can it be done in SQLite ?

是否可以直接从 SQL 查询中始终使用 2 个小数位进行格式化?如何在 SQLite 中完成?

Thanks.

谢谢。

回答by

You can use printfas:

您可以printf用作:

SELECT printf("%.2f", floatField) AS field FROM table;

for example:

例如:

sqlite> SELECT printf("%.2f", floatField) AS field FROM mytable;
3.56
2.40
4.78
3.00
sqlite>

回答by Appleman1234

Due to the way sqlite stores numbers internally,

由于sqlite内部存储数字的方式,

You probably want something like this

你可能想要这样的东西

select case when substr(num,length(ROUND(floatField,2))-1,1) = "." then num || "0" else num end from table;

回答by Oliver Pearmain

On older versions of SQLite that don't have PRINTFavailable you can use ROUND.

在没有PRINTF可用的旧版本 SQLite 上,您可以使用ROUND.

For example...

例如...

SELECT 
   ROUND(time_in_secs/1000.0/60.0, 2) || " mins" AS time,
   ROUND(thing_count/100.0, 2) || " %" AS percent
FROM
   blah

回答by Avagut

You could try Select Str(12345.6789, 12, 3)

你可以试试 Select Str(12345.6789, 12, 3)

displays: ' 12345.679'

显示: ' 12345.679'

( 3 spaces, 5 digits 12345, a decimal point, and three decimal digits (679). - it rounds if it has to truncate, (unless the integer part is too large for the total size, in which case asterisks are displayed instead.)

( 3 个空格,5 位 12345,一个小数点和三个小数位 (679)。 - 如果必须截断,则四舍五入,(除非整数部分对于总大小来说太大,在这种情况下,将显示星号。 )

for a Total of 12 characters, with 3 to the right of decimal point.

共 12 个字符,小数点右侧 3 个字符。