Converting an integer to a fixed-length string with leading zeros

79 Views Asked by At

Ideally I want toFixed function in JavaScript https://www.w3schools.com/jsref/jsref_tofixed.asp I know I can do this with Cypher like below.

WITH 3 AS inputNumber
RETURN
  CASE
    WHEN inputNumber < 10 THEN '0' + toString(inputNumber)
    ELSE toString(inputNumber)
  END AS formattedString;

but a simple APOC function would be better

2

There are 2 best solutions below

2
nimrod serok On BEST ANSWER

Try:

RETURN apoc.number.format(125.4, '0000.000') as value;

It returns: "0125.400"

Or to match your example:

RETURN apoc.number.format(3, '00') as value;

returns "03"

0
jose_bacoy On

The APOC function apoc.text.lpad will add '0' to the left of a string at a given width.

Ref:
https://neo4j.com/labs/apoc/4.3/overview/apoc.text/apoc.text.lpad/

apoc.text.lpad(text,count,delim) YIELD value - left pad the string to the given width

Example: RETURN apoc.text.lpad("3", 2, "0") AS output;

╒════════╕
│"output"│
╞════════╡
│"03"    │
└────────┘