Fixed determining correct prefix for negative units

This commit is contained in:
josdejong 2013-03-16 12:54:05 +01:00
parent 1ebb05254a
commit d2f605de23
2 changed files with 13 additions and 5 deletions

View File

@ -372,10 +372,10 @@ Unit.prototype.toString = function() {
// the absolute value of the log10 is closest to zero,
// though with a little offset of 1.2 for nicer values: you get a
// sequence 1mm 100mm 500mm 0.6m 1m 10m 100m 500m 0.6km 1km ...
var absValue = Math.abs(this.value / this.unit.value);
var bestPrefix = Unit.PREFIX_NONE;
var bestDiff = Math.abs(
Math.log(this.value / this.unit.value / bestPrefix.value) /
Math.LN10 - 1.2);
Math.log(absValue / bestPrefix.value) / Math.LN10 - 1.2);
var prefixes = this.unit.prefixes;
for (var p in prefixes) {
@ -383,8 +383,7 @@ Unit.prototype.toString = function() {
var prefix = prefixes[p];
if (prefix.scientific) {
var diff = Math.abs(
Math.log(this.value / this.unit.value / prefix.value) /
Math.LN10 - 1.2);
Math.log(absValue / prefix.value) / Math.LN10 - 1.2);
if (diff < bestDiff) {
bestPrefix = prefix;

View File

@ -7,7 +7,16 @@ var math = require('../../math.js'),
var unit1 = new Unit(5000, 'cm');
assert.equal(unit1, '50 m');
assert.equal(unit1.toString(), '50 m');
assert.equal(new Unit(5, 'kg').toString(), '5 kg');
assert.equal(new Unit('5kg').toString(), '5 kg');
assert.equal(new Unit('5 kg').toString(), '5 kg');
assert.equal(new Unit(' 5 kg ').toString(), '5 kg');
assert.equal(new Unit('5e-3kg').toString(), '5 g');
assert.equal(new Unit('5e+3kg').toString(), '5 Mg');
assert.equal(new Unit('-5kg').toString(), '-5 kg');
assert.equal(new Unit('-5mg').toString(), '-5 mg');
assert.equal(new Unit(null, 'kg').toString(), '1 kg');
assert.throws(function () {
Unit(2, 'inch');