To convert a number to a string in Groovy, you can use the toString()
method. This method is available on all numerical data types, such as int
, double
, and BigDecimal
.
Convert Number to String Examples in Groovy
Here are some examples of using the toString()
method to convert numbers to strings in Groovy:
// convert an int to a string int num = 42; String str = num.toString(); println("int: " + num + " -> string: " + str); // prints "int: 42 -> string: 42" // convert a double to a string double d = 3.14159; String str = d.toString(); println("double: " + d + " -> string: " + str); // prints "double: 3.14159 -> string: 3.14159" // convert a BigDecimal to a string BigDecimal bd = new BigDecimal("12345.6789"); String str = bd.toString(); println("BigDecimal: " + bd + " -> string: " + str); // prints "BigDecimal: 12345.6789 -> string: 12345.6789"
In this example, the program converts each numerical data type to a string using the toString()
method. Then, it prints the original value and the resulting string to the console using the println()
method. This produces the output shown in the comments for each example.