0

I want to remove decimal from number in javascript: Something like this:

12 => 12
12.00 => 1200
12.12 => 1212
12.12.12 => error: please enter valid number.

I can not use Math.round(number). Because, it'll give me different result. How can I achieve this? Thanks.

RNK
  • 5,582
  • 11
  • 65
  • 133

3 Answers3

5

The simplest way to handle the first three examples is:

function removeDecimal(num) {
    return parseInt(num.toString().replace(".", ""), 10);
}

This assumes that the argument is a number already, in which case your second and fourth examples are impossible.

If that's not the case, you'll need to count the number of dots in the string, using something like (trick taken from this question):

(str.match(/\./g) || []).length

Combining the two and throwing, you can:

function removeDecimal(num) {
    if ((num.toString().match(/\./g) || []).length > 1) throw new Error("Too many periods!");

    return parseInt(num.toString().replace(".", ""), 10);
}

This will work for most numbers, but may run into rounding errors for particularly large or precise values (for example, removeDecimal("1398080348.12341234") will return 139808034812341230).

If you know the input will always be a number and you want to get really tricky, you can also do something like:

function removeDecimal(num) {
    var numStr = num.toString();
    if (numStr.indexOf(".") === -1) return num;
    return num * Math.pow(10, numStr.length - numStr.indexOf(".") - 1);
}
Community
  • 1
  • 1
ssube
  • 47,010
  • 7
  • 103
  • 140
  • Or `+(num+'').replace('.','')` :) – RienNeVaPlu͢s Feb 25 '15 at 18:13
  • Why not simply `parseInt(num.toString().replace(/\./, ''), 10)`? That way you only replace the first dot, and then parse it as an integer. Your regex will match `,`'s and not `.`'s. – h2ooooooo Feb 25 '15 at 18:13
  • @h2ooooooo The OP asked to error out if more than one dot is present, so I've added that logic. – ssube Feb 25 '15 at 18:14
  • The second example is also impossible with a number. The number `12.00` is the number `12`, so it won't be formatted into `"12.00"`. – Guffa Feb 25 '15 at 18:14
  • @ssube You haven't though - you've checked for `,` (a comma) and not `.` (a dot). **Edit**: I see you've fixed it :) – h2ooooooo Feb 25 '15 at 18:14
3

You can use the replace method to remove the first period in the string, then you can check if there is another period left:

str = str.replace('.', '');
if (str.indexOf('.') != -1) {
  // invalid input
}

Demo:

function reformat(str) {
  str = str.replace('.', '');
  if (str.indexOf('.') != -1) {
    return "invalid input";
  }
  return str;
}

// show in Stackoverflow snippet
function show(str) {
  document.write(str + '<br>');
}

show(reformat("12"));
show(reformat("12.00"));
show(reformat("12.12"));
show(reformat("12.12.12"));
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1

How about number = number.replace(".", ""); ?

firefoxuser_1
  • 1,793
  • 13
  • 22