所以我有一个带有数字值的var,我想在第三个最后位置加上'='符号
var num = 98564;会成为
985=64通过谷歌搜索我来到这个功能
String.prototype.insert = function (index, string) { if (index > 0) return this.substring(0, index) + string + this.substring(index, this.length); else return string + this; }我认为它会完成我的工作,但我也希望保持条件,如果var num = 98; (2位数)然后输出应为0=98
你能帮我修改一下这个功能吗? 还指导我在PHP中做同样的事情(你知道的任何内置函数吗?)谢谢!
So I have a var with value in digits and i want to add '=' sign at the third last position such that
var num = 98564;would become
985=64by googling I came accross this function
String.prototype.insert = function (index, string) { if (index > 0) return this.substring(0, index) + string + this.substring(index, this.length); else return string + this; }I think it will do my job, but I also want to keep a condition that if var num = 98; (2 digits) then the output should be 0=98
can you help me modifying that function? also guide me to do the same in PHP (any inbuilt function that you know?) Thanks!
最满意答案
PHP
function new_num($int) { $new_num = (isset($int) ? (strlen($int) > 2 ? substr_replace($int, '=', strlen($int)-2, 0) : '0=' . $int) : null); return $new_num; } $num = 16000; $new_num = new_num($num);该函数将检查输入是否已设置(虽然在函数中看起来有点多余,因为变量是必需的,我把它放在那里,以防你不想让它成为函数)然后检查是否有长度输入大于2.如果大于2,则会插入“=”,否则会在前面添加“0 =”。 javascript基本上是做同样的事情,但只是要注意它必须转换为字符串,以使用子字符串,长度等操纵它。
使用Javascript:
var num = 16000; num = num.toString(); if (num.length > 2) { var new_num = num.substring(0, num.length-2) + '=' + num.slice(-2); } else { var new_num = '0=' + num; }PHP
function new_num($int) { $new_num = (isset($int) ? (strlen($int) > 2 ? substr_replace($int, '=', strlen($int)-2, 0) : '0=' . $int) : null); return $new_num; } $num = 16000; $new_num = new_num($num);The function will check that the input is set (although it's a bit redundant in a function seeing as the variable is required, I put it there in case you didn't want it to be a function) and then check if the length of the input is greater than 2. If greater than 2, it will insert the "=", otherwise it will add "0=" to the front. The javascript is doing essentially the same thing but just to note it has to be converted to a string to manipulate it with substring, length, etc.
Javascript:
var num = 16000; num = num.toString(); if (num.length > 2) { var new_num = num.substring(0, num.length-2) + '=' + num.slice(-2); } else { var new_num = '0=' + num; }更多推荐
发布评论