Math. round was used to make an effect in the unit yesterday. The layer spreads to the surrounding area. After that, I suddenly came up with a small idea: How did I write this method in JS?
After thinking about it, start to convert the number into a string:
String(11.2);// return "11.2"
Then, use split to obtain the decimal point and convert the string to an integer or a decimal point:
String(11.2).split(".")//return ["11", "2"];
Then we can determine the decimal part. We can use the substring method to obtain the first character of the string to see whether it is a carry or a back digit:
String(11.234).split(".")[1].substring(0,1);//return "2";
Then convert and judge through parseInt:
parseInt(String(11.234).split(".")[1].substring(0,1)) < 5;//return true;
The final processing is done by judging positive and negative values:
parseInt(String(11.234).split(".")[0].substring(0,1))>0;//return false;
The following is the full code:
// The code and ideas come from another friend ~
Function round (arg) {if (parseInt (String (arg ). split (". ") [1]. substring (0, 1) <5) {return parseInt (String (arg ). split (". ") [0]);} else {if (parseInt (String (arg ). split (". ") [0])> 0) {return parseInt (String (arg ). split (". ") [0]) + 1;} else {return parseInt (String (arg ). split (". ") [0])-1 ;}}}
The Writing seems to be finished, but I suddenly thought about it. Can I do this without using the JS method?
So I made a simple attempt, first of all, how to get the content after the decimal point without using the method? If you cannot use type conversion but can only use basic operations, it is difficult to obtain. In fact, what I want is not to obtain this number, but to determine whether the number is greater than 0.5. This is much more convenient:
Var round_x = (10 * arg) % 10)> 0 )? (10 * arg) % 10):-(10 * arg) % 10); // obtain the number after the decimal point * 10
After obtaining this number, we can perform the most basic determination to obtain the result. The Code is as follows:
function round (arg) { var round_x = (((10 * arg) % 10) > 0) ? ((10 * arg) % 10) : -((10 * arg) % 10); if (round_x < 5) { return arg - (arg % 1); }else{ return (arg > 0 ? (arg - (arg % 1) +1) : arg - (arg % 1) - 1); }}
Through a simple arithmetic operation, we can get the result of round.
The code is relatively simple. If you want to have better code, you can communicate with each other. Thank you ~