formatDimension function
String
formatDimension(
- double mm,
- DisplayUnit unit, {
- DecimalSeparator decimalSeparator = DecimalSeparator.point,
A dimension's text for a length of mm in the page's display unit
(spec 11 D9, decision 7): no unit symbol, the page's decimalSeparator
(spec Q0 T1; . in the examples below), no grouping, each unit at its
plan precision:
- mm, to 1 mm: the integer (
3450); - cm, to 0.1 cm: one decimal, always (
345.0, R-14); - m, to 0.01 m: two decimals, always (
3.45,14.00); - inches, to 1/8": whole inches then a reduced fraction, no mark
(
136 3/8,136,0 1/4, R-15); - feet-inches, to 1/4":
F'-I"orF'-I N/D", the fraction reduced (11'-4 1/4",12'-0",0'-0 1/2"); the marks are the notation that separates feet from inches, not a unit symbol (R-15).
The total is rounded (roundHalfUp) in quanta of the precision before
it is split into whole units and a fraction, so a carry reaches the next
unit: 143 7/8" is 575.5 quarters and prints 12'-0", never 11'-12".
The magnitude of mm is formatted. Only cm and m print a decimal
separator; mm prints an integer, inches and feet-inches fractions.
Implementation
String formatDimension(double mm, DisplayUnit unit,
{DecimalSeparator decimalSeparator = DecimalSeparator.point}) {
final v = mm.abs();
switch (unit) {
case DisplayUnit.millimeters:
return '${roundHalfUp(v, 1)}';
case DisplayUnit.centimeters:
final n = roundHalfUp(v, 1); // millimetres, tenths of a cm
return '${n ~/ 10}${decimalSeparator.char}${n % 10}';
case DisplayUnit.meters:
final n = roundHalfUp(v, 10); // hundredths of a metre
return '${n ~/ 100}${decimalSeparator.char}'
'${(n % 100).toString().padLeft(2, '0')}';
case DisplayUnit.inches:
final n = roundHalfUp(v, 25.4 / 8); // eighths of an inch
return '${n ~/ 8}${_fraction(n % 8, 8)}';
case DisplayUnit.feetInches:
final n = roundHalfUp(v, 25.4 / 4); // quarters of an inch
final feet = n ~/ 48, rest = n % 48;
return "$feet'-${rest ~/ 4}${_fraction(rest % 4, 4)}\"";
}
}