dart-latlong
dart-latlong copied to clipboard
Working with doubles as string is wrong
https://github.com/MikeMitterer/dart-latlong/blob/0325c7d911b620c4f7efe9c9136a20ea7730c837/lib/latlong.dart#L92-L111
When dec
is 53.0335
then splitting a double into two parts, that then get parsed as integers is wrong!
The fractionalPart 0335
becomes an integer - 335, and then "recreating" a double by doing 0.$fractionalPart
is simply silly.
0.335 != 0.0335
final String sexa2 = decimal2sexagesimal(-42.883891);
expect(sexa2, '42° 53\' 02.01"'); // got '42° 53\' 20.08"'
The right way of doing this is:
/// Converts a decimal coordinate value to sexagesimal format
///
/// final String sexa1 = decimal2sexagesimal(51.519475);
/// expect(sexa1, '51° 31\' 10.11"');
///
/// final String sexa2 = decimal2sexagesimal(-42.883891);
/// expect(sexa2, '42° 53\' 02.01"');
///
String decimal2sexagesimal(final double dec) {
if (dec == null) throw new ArgumentError.notNull('dec');
final buf = new StringBuffer();
final double absDec = dec.abs();
final int deg = absDec.floor();
buf.write(deg.toString() + '°');
final double mins = (absDec - deg) * 60.0;
final int min = mins.round();
buf.write(' ' + zeroPad(min) + "'");
final double secs = (mins - mins.floorToDouble()) * 60.0;
final int sec = secs.round();
final int frac = ((secs - secs.floorToDouble()) * 100.0).round();
buf.write(' ' + zeroPad(sec) + '.' + zeroPad(frac) + '"');
return buf.toString();
}
/// Pads a number with a single zero, if it is less than 10
String zeroPad(num number) => (number < 10 ? '0' : '') + number.toString();
Sorry, I'm calling this function a lot, so StringBuffer
makes sense for me.