0

This is a unit converter in JS. When someone converts volumes, the input volume first gets converted to litres, and then to every other unit. The computed values automatically get displayed in the input fields. For that purpose I created an object to store the converting values, like so:

var volumes={
    cbm: 1000,
    ltr: 1,
    ml: 0.001,
    barrel: 158.9873,
    gal: 3.785411784,
    pint: 0.473176473,
    floz: 0.0295735295625,
    //and so on
};

And for the conversion between the units of one system I tried this:

var volumes={
  impfloz: 0.0284130642624675,
  imppint: this.impfloz*20,
  impbarrel: this.impfloz*5600,
  impgal: this.impfloz*160
};

But it didn’t work. When I type in a value, e.g. in the input field “Imperial-Barrel”, all other input fields display: NaN. Do I really have to write functions for each of these? It would make the code much more complicated and more difficult to read. Is there a way to get the object members to automatically apply the desired mathematical operation?

quacodas
  • 273
  • 1
  • 9

1 Answers1

1

No, you can't do that. But what's wrong with

var impfloz = 0.0284;
var volumes={
    impfloz: impfloz,
    imppint: impfloz*20,
    impbarrel: impfloz*5600,
    impgal: impfloz*160
};

If you're worried about polluting the global namespace with the impfloz variable, you could wrap the whole thing in an IIFE.

this has meaning only within a function, where it refers to the object against which the function was invoked.

  • Thanks for your information. It works, but i think it’s not very elegant… But can you also explain me why, when i type in 1000000000000 in the barrel field, the gallon field shows 34999999999999.992 instead of 35000000000000? I mean that was why I tried to do this. Does JS automatically cuts off some decimals and if so, is there any way to prevent that? – quacodas Sep 05 '14 at 18:00
  • @quaductas JS numbers are "double precision floating point numbers" and they're capped at about 2^53, if you need higher values you'd have to use a library. – Benjamin Gruenbaum Sep 05 '14 at 19:56