uce/site/doc/pages/to_s64.txt

42 lines
1.4 KiB
Plaintext

:sig
s64 DValue::to_s64(s64 default_value = 0) const
:params
default_value : returned when the value is missing or cannot be parsed as a number
return value : the value as a signed 64-bit integer, or `default_value`
:see
>types
0_DValue
to_u64
to_f64
to_bool
to_string
:content
Reads a `DValue` value as a signed integer. This is a read accessor: it is `const`, never creates or modifies nodes, and dereferences internal references automatically.
String values are trimmed and parsed permissively: plain integers, floating-point forms (truncated toward zero), and the boolean words understood by `to_bool()` (`yes` reads as `1`) all convert. Results outside the `s64` range clamp to the range boundaries. Boolean values become `1` or `0`.
`default_value` is returned when:
- the node is unset or holds an empty string
- the string does not parse as a number (`"not-a-number"`)
- the node is map-shaped with more than one entry, or an unresolvable reference
A map-shaped node with exactly one entry unwraps to that entry's value before converting — this matches how single-value rows from query results read.
## Example
```cpp
s64 page = context.get["page"].to_s64(1);
s64 limit = context.cfg.get_by_path("app/page_size").to_s64(25);
```
`json_decode()` stores JSON numbers as string-valued nodes, so this is the normal way to consume decoded numeric fields.
## Related Concepts
- PHP: `intval()` with a fallback
- JavaScript: `parseInt(x) || fallback`