I have to convert a value from the old unit into the new unit.
The old unit can be mg/l and the new unit can be ug/ml. The oldValue is 8 mg/l. When I use the converter of google it shows me that the value doesn't change. In my calculation the value changes from 8mg/l to 1 ug/ml, what is absolutely wrong.
Most probably I am using the incorrect formula to calculate the new value.
This is my current approach:
At first, I declared the possible units with objects and the potencies:
private potenciesMass = {
kg: 1,
g: 1000,
mg: 1000000,
µg: 1000000000,
ug: 1000000000,
pg: 1000000000000,
};
private potenciesCapacity = {
l: 1,
dl: 10,
ml: 1000,
ul: 1000000,
nl: 1000000000,
pl: 1000000000000,
fl: 1000000000000000,
};
In the next step I read out the potency of each unit and calculate the new value with them. At the end I divide both values.
let potencyFirstOld = this.getPotencyValue(oldUnitSplitted[0]);
let potencyFirstNew = this.getPotencyValue(newUnitSplitted[0]);
// Second Unit
let potenceySecondOld = this.getPotencyValue(oldUnitSplitted[1]);
let potenceySecondNew = this.getPotencyValue(newUnitSplitted[1]);
let firstValue = this.convertMultipleTypes(
potencyFirstOld,
potencyFirstNew,
value
);
let secondValue = this.convertMultipleTypes(
potenceySecondOld,
potenceySecondNew,
value
);
value = firstValue / secondValue;
Anyone have an idea how I can convert the old value into the new value by the units?
Edit: New Code
private convertMultipleTypes(
potencyOld: number,
potencyNew: number,
value: number
): number {
let potenceDifference = 0;
let potence: number;
if (potencyOld < potencyNew) {
potenceDifference =
potencyNew.toString().length - potencyOld.toString().length;
potence = this.calculatePotence(potenceDifference);
return value / potence;
}
potenceDifference =
potencyOld.toString().length - potencyNew.toString().length;
potence = this.calculatePotence(potenceDifference);
return value * potence;
}
private calculatePotence(potenceDifference: number): number {
let potence = "1";
for (let i = 0; i < potenceDifference; i++) {
potence += 0;
}
return Number(potence);
}