Numbers in YAML
Take your programming skills to the next level with interactive lessons and real-world projects.
Explore Coddy →YAML supports various number formats, making it versatile for representing numerical data. Understanding how to use numbers in YAML is crucial for creating accurate and efficient configurations.
Integer Numbers
YAML allows you to represent whole numbers (integers) in multiple ways:
age: 30
population: 7_000_000_000
hex: 0xFF
octal: 0o77
binary: 0b1010
Note the use of underscores for readability in large numbers and the prefixes for different number bases.
Floating-Point Numbers
For decimal numbers, YAML supports standard and scientific notation:
pi: 3.14159
avogadro: 6.022e23
tiny: 1.0e-10
Special Number Values
YAML also recognizes special number values:
- Infinity:
positive_infinity: .inf - Negative Infinity:
negative_infinity: -.inf - Not a Number:
not_a_number: .nan
Best Practices
- Use underscores for readability in large numbers
- Be consistent with number formats throughout your YAML file
- Consider using scientific notation for very large or small numbers
- Be aware that some parsers may have limitations on number sizes
Numbers in Complex Structures
Numbers can be used in various YAML structures, including lists and dictionaries:
measurements:
- 10.5
- 20.3
- 15.7
coordinates:
x: 100
y: 200
z: 300
Type Inference and Explicit Typing
YAML typically infers the type of a number, but you can explicitly specify the type using tags:
implicit_integer: 42
explicit_integer: !!int 42
explicit_float: !!float 42.0
This can be particularly useful when working with YAML parsing in different programming languages.
Conclusion
Understanding number representation in YAML is essential for creating accurate and efficient configurations. By leveraging different number formats and following best practices, you can ensure your YAML files are both readable and precise.
For more information on related topics, check out YAML Booleans and YAML Strings.