Forzaferrarileo
Forzaferrarileo

Reputation: 25

javascript : casting int to char trouble

I have a small script that read delta X and Y of a joystick and next cast they into character:

var a =deltaX.toString();
var b =deltaY.toString();
outputEl.innerHTML  = '<b>Result:</b> '
    + a
    + b;    
var comando = a + b ;

the trouble is I need number lower than 10 and -10 , to be 2 characters , so for example 5 , to be 05 . what's should be a good way to add the zero in the numbers lower than 10 and -10 ?

Upvotes: 0

Views: 177

Answers (2)

Jacob Bundgaard
Jacob Bundgaard

Reputation: 1085

You can do it with a ternary operator (inline if) by looking at the length-property:

outputEl.innerHTML  = '<b>Result:</b> '
            + a.length > 1 ? a : '0' + a
            + b.length > 1 ? b : '0' + b;

Upvotes: 1

Jordan Scales
Jordan Scales

Reputation: 2717

var a;

if (deltaX < 10) {
  // one digit
  a = '0' + deltaX;
} else {
  a = deltaX.toString();
}

Note that this doesn't handle the negative portion, but I am showing a proof of concept. Since your numbers are so small, you can pad with a simple if statement, rather than an air-tight method to pad zeros.

Upvotes: 2

Related Questions