We wish to format the string representation of numbers in a certain way typically for display purposes.
We will cover two common scenarios which are:
This section is concerned with the string representation of numbers. See Numeric for a coverage of the display settings of numbers.
We wish to make sure that numbers are displayed “plainly” without applying scientific notation.
In this example, we wish to create a new column col_2
that is a string representation of the
numeric column col_1
while ensuring that the numbers are displayed without scientific notation.
SELECT col_1,
FORMAT('%f', col_1) col_2
FROM table_1;
Here is how this works:
1000
as 1e+03
and is often triggered automatically when
displaying large numbers.FORMAT()
while setting the format specifier to f
which means decimal notation.We wish to add comma separators between each three digits in the string representation of large numbers.
In this example, we wish to create a new column col_2
that is a string representation of the
numeric column col_1
with commas added between every three digits.
SELECT col_1,
FORMAT("%'d", col_1) col_2
FROM table_1;
Here is how this works:
1000000
is displayed as 1,000,000
.FORMAT()
while setting the format specifier to d
which means decimal
integer.'
before the format specifier as a flag to add commas after every three digits.Extension: Adding Padding
SELECT col_1,
FORMAT("%'*d",21, col_1) col_2
FROM table_1;
Here is how this works:
*
before the format specifier (d
in this
case) and then passing the desired width as an argument to FORMAT()
(21 in this example).We wish to specify the number of decimal places (after the decimal point) to display in a string representation of a floating point number.
In this example, we wish to create a new column col_2
that is a string representation of the
numeric column col_1
with two decimal places after the point for each value.
SELECT col_1,
FORMAT('%.2f', col_1) col_2
FROM table_1;
Here is how this works:
FORMAT()
while setting the format specifier to f
which means decimal notation..2
specifies the minimum number of digits to the right of the decimal point.FORMAT()
as
follows : FORMAT('%.*f', precision ,col_1)
.Extension: String to Numeric to String
SELECT col_1,
FORMAT('%.2f', SAFE_CAST(col_1 AS FLOAT64)) col_2
FROM table_1;
Here is how this works:
col_1
is a string, we will first need to convert it to a numeric data type, so
we may round it.SAFE_CAST()
to convert a string to a float data type.
See Numeric.