开发者

remove '.' of an float [closed]

It's difficult to tell what is being asked here. This question is a开发者_如何学JAVAmbiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

548.705078125 output -> 548705078125

What's the best way to do this, not using regex or .replace('.','')?


Try this:

Number((548.705078125).toString().split(".").join(""))


Look, no horrible, nasty string functions or regex!

function noStringsOrRegexOrDecimals(num) {
  while (num % 1 !== 0) {
    num *= 10;
  };
  return num;
}

noStringsOrRegexOrDecimals(548.705078125);

Yes, I'm aware that this is not a very useful function to have in your toolkit (although it is fast). And that it breaks for some numbers because of how floating point math works, and that it won't work in our glorious octal future to come.


If you're not using replace() or regex(), then what about split()?

var str = '548.705078125';
str = str.split(".");
str = str[0]+str[1];


Those are weird restrictions. At the end of this c === 548705078125:

var f = 548.705078125;
var c = Math.floor(f);
f = f.toString();
for(var i = 1; (c = Math.floor(c/10)) > 0; i++);
c = parseInt(f.substring(0, i)+f.substring(i+1));


I can't believe nobody has suggested the obvious jQuery way to do this, so that you don't need JavaScript string or maths functions:

function removeDot(num) {
  var result = $.ajax({
                       url: "removeDot.php",
                       type: "POST",
                       data: {"num" : num},
                       dataType: "text",
                       async:false
                     }).responseText;
  return Number(result);
}

console.log(removeDot(548.705078125)); // output -> 548705078125 

I leave the implementation of "removeDot.php" as an exercise for the reader...


You need the number to be an int... so you can pass it to a function as an int.... are you sure you don't need the following instead?

var num = 2395847.3428345;
Math.floor(num); // result is 2395847


Make it into a String and loop over all chrs in it and look for chr == "."

Never heard of a case where you shouldnt use regexp or replace though..


var n = 548.705078125.toString();
var i = n.substr(0, n.indexOf('.')) + n.substr(n.indexOf('.')+1);
alert(i);


No regular expressions!

var num = 548.705078125;

function remove_decimal(num)
{
    var numStr = "" + num;
    var decimalIndex = numStr.indexOf('.');
    return num * Math.pow(10, (numStr.length - (decimalIndex + 1)));
}

remove_decimal(num) -> 548705078125


Assuming your number is already a float (for calling into a function that requires integers, I assume), you can use this:

floor(1e9 * x);  // where x is 548.705078125 in your case

floor will spare you any strange precision issues from your processor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜