Reputation: 987
I have a bunch of geojson data with may points being the exact same.
30.9694313
How would I isolate the last number and random increment it or decrement it landing on either 30.9694314 or 30.9694312?
I guess I could add or subtract 0.0000001, but how to handle this in the event of a dynamic float length?
Upvotes: 1
Views: 591
Reputation: 987
Thanks for your help guys. This is what I came up with. I imagine there might be a cleaner way but this seems to work for me. Thanks for putting me on the right track.
noiselocation('-30.12345');
function noiselocation(coord){
//num to string and strip special chars
var coordstr = coord.toString();
console.log('string: ' + coordstr);
//get length
var coordstrlength = coordstr.length-1;
console.log('length: ' + coordstrlength);
//get last char
var coordlastchar = coordstr.charAt(coordstrlength);
console.log('last char: ' + coordlastchar);
//turn back to number
coordlastnum = parseInt(coordlastchar);
console.log('last num: ' + coordlastnum);
//randomly increment up or down
var randswitch = Math.floor(Math.random() * 2) + 1;
if(randswitch == "1"){
coordlastnum++;
}else{
coordlastnum--;
}
console.log('last num after rand: ' + coordlastnum);
//replace last char on string
var newcoordstr = coordstr.slice(0, -1) + coordlastnum;
console.log('new string: ' + newcoordstr);
//turn string back to num
newcoordnum = parseFloat(newcoordstr);
console.log('new num: ' + newcoordstr);
}
Upvotes: 1
Reputation: 387
One way to do this would be to get a String representation of your float, and then parse the last digit as an integer. Then, you could increment/decrement it, add it back to the substring of your String to replace the old last digit, and parse it as a float. Not sure if this would be the most efficient way to do it, but it's the first thing to pop into my head.
Edit: some methods to help you (links to MDN)
Upvotes: 2