Shivi
Shivi

Reputation: 1085

Round the value in Javascript

I have scenario where if user enters for example 000.03, I want to show the user it as .03 instead of 000.03. How can I do this with Javascript?

Upvotes: 1

Views: 470

Answers (6)

KooiInc
KooiInc

Reputation: 123026

How about:

function showRounded(val) {
    var zero = parseInt(val.split('.')[0],10) === 0;
    return zero ? val.substring(val.indexOf('.')) : val.replace(/^0+/,'') );
}
console.log(showRounded('000.03')); //=> ".03"
console.log(showRounded('900.03')); //=> "900.03"
console.log(showRounded('009.03')); //=> "9.03"

Or adjust Álvaro G. Vicario's solution to get rid of leading zero's into:

String(parseFloat("090.03")).replace(/^0+\./, ".")

Upvotes: 1

Mathias Bynens
Mathias Bynens

Reputation: 149804

This function will take any string and try to parse it as a number, then format it the way you described:

function makePretty(userInput) {
  var num,
      str;
  num = parseFloat(userInput); // e.g. 0.03
  str = userInput.toString();
  if (!isNaN(num) && str.substring(0, 1) === '0') {
    str = str.substring(1); // e.g. .03
  } else if (isNaN(num)) {
    str = userInput; // it’s not a number, so just return the input
  }
  return str;
}

makePretty('000.03'); // '.03'
makePretty('020.03'); // '20.03'

It you feed it something it cannot parse as a number, it will just return it back.

Update: Oh, I see If the single leading zero needs to be removed as well. Updated the code.

Upvotes: 1

Steven Ryssaert
Steven Ryssaert

Reputation: 1967

This actually is trickier than it first seems. Removing leading zero's is not something that is standard Javascript. I found this elegant solution online and edited it a bit.

function removeLeadingZeros(strNumber)
{
  while (strNumber.substr(0,1) == '0' && strNumber.length>1)
  {
    strNumber = strNumber.substr(1);
  }
  return strNumber;
}

userInput = "000.03";
alert(removeLeadingZeros(userInput));

Upvotes: 2

David Tang
David Tang

Reputation: 93714

You can convert a string into a number and back into a string to format it as "0.03":

var input = "000.03";
var output = (+input).toString(); // "0.03"

To get rid of any leading zeroes (e.g. ".03"), you can do:

var input = "000.03";
var output = input.substr(input.indexOf(".")); // ".03"

However, this improperly strips "20.30" to ".30". You can combine the first two methods to get around this:

var input = "000.03";
var output = Math.abs(+input) < 1 ?
    input.substr(input.indexOf(".")) :
    (+"000.03").toString();

Upvotes: 0

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146660

You can use a regular expression:

"000.03".replace(/^0+\./, ".");

Adjust it to your liking.

Upvotes: 2

trickwallett
trickwallett

Reputation: 2468

Assuming your input's all the same format, and you want to display the .

user = "000.03";
user = user.substring(3);

Upvotes: 0

Related Questions