英文:
How to convert integer value to float in json column in MariaDB?
问题
I need to convert values of $.fonts_size
json property to float.
Currently there are integer values such as 1
and I need them to become 1.0
to make my app treat them as double.
In this case json like:
{
"fonts_size": 1
}
Should be converted to:
{
"fonts_size": 1.0
}
Is that possible to do within SQL in MariaDB?
I tried solutions like this:
SELECT JSON_EXTRACT(
JSON_SET(
settings,
"$.fonts_size",
CAST(
JSON_EXTRACT(
settings,
"$.fonts_size"
)
AS FLOAT
)
),
'$.fonts_size'
)
FROM blocks WHERE JSON_TYPE(JSON_EXTRACT(settings, "$.fonts_size")) = "INTEGER"
However this does not make a difference.
Also tried concatenating ".0" but this results in string instead of double
英文:
I need to convert values of $.fonts_size
json property to float.
Currently there are integer values such as 1
and I need them to become 1.0
to make my app treat them as double.
In this case json like:
{
"fonts_size": 1
}
Should be converted to:
{
"fonts_size": 1.0
}
Is that possible to do within SQL in MariaDB?
I tried solutions like this:
SELECT JSON_EXTRACT(
JSON_SET(
settings,
"$.fonts_size",
CAST(
JSON_EXTRACT(
settings,
"$.fonts_size"
)
AS FLOAT
)
),
'$.fonts_size'
)
FROM blocks WHERE JSON_TYPE(JSON_EXTRACT(settings, "$.fonts_size")) = "INTEGER"
However this does not make a difference.
Also tried concatenating ".0"
but this results in string instead of double
答案1
得分: 1
这是一种将整数转换为带有小数点后一位的DECIMAL
的方法:
SELECT CAST(JSON_EXTRACT(
settings,
"$.fonts_size"
) AS DECIMAL(5,1)),
JSON_TYPE(JSON_EXTRACT(settings, "$.fonts_size"))
FROM blocks
WHERE JSON_TYPE(JSON_EXTRACT(settings, "$.fonts_size")) = "INTEGER";
DECIMAL(5,1)
表示一个数字总共有5位数,小数点右边有1位数(因此,左边有4位,右边有1位)。
英文:
This is a way to do it by casting the integer into DECIMAL
with one digit after the decimal point:
SELECT CAST(JSON_EXTRACT(
settings,
"$.fonts_size"
) AS DECIMAL(5,1)),
JSON_TYPE(JSON_EXTRACT(settings, "$.fonts_size"))
FROM blocks
WHERE JSON_TYPE(JSON_EXTRACT(settings, "$.fonts_size")) = "INTEGER"
DECIMAL(5,1)
means a number having 5 digits altogether, with 1 of them to the right of the decimal point. (So, 4 left, 1 right.)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论