Convert Number to String?

I have a need to convert a number in a variable to text which I will concat with another string and store in a different string variable. I’ve had a dig through the Expressions documentation but I can’t find a way to transform the numeric value to string.

Can anyone help?

EDIT: Never mind. I realized I can accomplish what I need simply by setting the value of the string variable manually and appending the number variable. Duh.

You could also do this with the replace() function in an expression as it attempts some implicit conversions.

myNumber = 2
replace("The value is {x} now!", "{x}", myNumber)

You could also use the stringify() method which JSON stringifies the input. In the case of a number, the output is the raw string value for the number.

myNumber = 2
concat("The value is ", stringify(myNumber), " now!")
1 Like

Thanks Josh. I’ll take a look at those options. I just noticed my approach mentioned in my EDIT above is flawed anyway. If the number ends in a 0 it is dropped once added to the string.

@josh I tried both your alternatives and in both cases they also drop trailing zeroes. Any ideas how to stop that?

Do you mean decimal values with trailing zeros? Or can you share an example value?

Yes, sorry for not being clearer.

For example, if I have a number = 137.90, once I process it through the methods we’ve discussed it becomes 137.9 and 138.00 becomes 138.

I don’t believe we have a function exposed that outputs a number in a fixed precision. Perhaps some sort of function that does this is warranted. :thinking:

In the meantime, you could write an expression to stringify your number, split it at the decimal, and zero-pad the right side.

myNumber = 2
str = stringify(myNumber)
parts = split(str, ".")
integers = parts[0]
decimals = count(parts) > 1 ? parts[1] : ""
decimals = left(concat(decimals, "00000"), 2)
concat(integers, ".", decimals)
1 Like

Perhaps Josh. For context, if it’s not obvious, my number is a dollars and cents value.

I will give this a go. I really appreciate the guidance. I’m reasonably technical but never been a developer and some coding logic and syntaxes are difficult for me without good directions.

1 Like

This did it.

Thank you!

1 Like

We added a new toFixed() method that will do this for you:

  • toFixed(input, digits) - takes a numeric input along with a number of digits to display and formats the number as a string with the specified number of digits (rounding if necessary)
    • input: numeric input value
    • digits: fixed number of digits after the decimal place to display (0-100)

Example:

toFixed(12.345, 2) #// "12.35"
toFixed(12.345, 0) #// "12"
toFixed(120, 2)    #// "120.00"
1 Like

Wow. That’s just awesome Josh. I will convert to this shortly.

Thank you!

EDIT: Implemented in my rule and working like a dream.

1 Like