1

I have a calculator that I'm building where the user can convert united back and forth between imperial and metric.

My code for this is as follows:

oldVal = jQuery(this).val();
oldVal = parseFloat(oldVal);
newConvertedVal = parseFloat((oldVal * 0.1589873).toFixed(2));
jQuery(this).val(newConvertedVal);

I'm using .toFixed(2) because I'm trimming the number to 2 decimal places. My only issue with this is that if I convert back by using:

newConvertedVal = parseFloat((oldVal / 0.1589873).toFixed(2));

Then it won't go back to exactly the same number because these are being rounded.

I'd like to stop using .toFixed(2) for this reason, but then my application will be showing some lengthy floating point numbers.

Is there a way around using the full numbers for conversions, but only showing the number to the last 2 decimal places? I've looked at using the pattern attribute in html (https://www.w3schools.com/tags/att_pattern.asp) but this isn't supported by Safari.

Any ideas?

1
  • There is mathematically nothing you can do about it, the way you do it... Since you squarely want to drop some decimals, the conversion back just can't work. You have to keep the "real" result in a variable for conversion back... And show another that has decimals dropped. Oct 6, 2018 at 15:58

2 Answers 2

0

My only issue with this is that if I convert back...

Since you squarely want to drop some decimals, the conversion back just won't work. It is about maths more than coding.

So you have to keep the "real" result in a variable for conversion back... And show another that has decimals dropped.

oldVal = jQuery(this).val();
oldVal = parseFloat(oldVal);
newConvertedVal = oldVal * 0.1589873;  // Keep that one!

newConvertedVal_toDisplay = newConvertedVal.toFixed(2);
jQuery(this).val(newConvertedVal_toDisplay);

And then:

// Conversion back
converterdBack = (newConvertedVal / 0.1589873);  // Or squarely use oldVal !?!

If that is inside a sub function and you need to store that number for later conversion back, you have options: localStorage, data-* attribute, a result object...

0

I'd use the data function to store the number:

oldVal = jQuery(this).val();
oldVal = parseFloat(oldVal);
var val = (oldVal * 0.1589873);
jQuery(this).data("numberValue", val);
jQuery(this).val(parseFloat(val.toFixed(2)));

You can grab it back later this way (assuming this is still in context at that point):

var theValue = parseFloat(jQuery(this).data("numberValue"));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.