winter 大大的前端进阶训练营 第三周 字符串与数字之间的互相转化作业
<!--
* @Date: 2020-05-26 18:58:36
* @LastEditors: xuchao
* @LastEditTime: 2020-05-26 20:52:08
* @FilePath: /暂时性缓存区/stringToNumber.html
-->
<script>
function convertStringToNumber(string, radix = 10) {
// 十进制以上的数不支持 (eg: ABCDFG)
if (radix > 10) {
return
}
// 字符串里面s是否有 e|E
let flag = /e|E/.test(string)
if (!flag) {
let chars = string.split('')
let number = 0
let i = 0
while (i < chars.length && chars[i] != '.') {
number = number * radix
number += chars[i].codePointAt(0) - '0'.codePointAt(0)
i++
}
if (chars[i] === '.') {
i++
}
let fraction = 1
while (i < chars.length) {
fraction /= radix
number += (chars[i].codePointAt(0) - '0'.codePointAt(0)) * fraction
i++
}
return number
} else {
let logNumber = Number(string.match(/\d+$/)[0])
let number = string.match(/^[\d\.]+/)[0].replace(/\./, '')
if (/e-|E-/.test(string)) {
return Number(number.padEnd(logNumber + 1, 0))
} else {
return Number(
number.padStart(logNumber + number.length, 0).replace(/^0/, '0.')
)
}
}
}
// document.write(convertStringToNumber('3.4556645445E20'))
function convertNumberToString(number, radix) {
let integer = Math.floor(number)
let fraction = String(number).match(/\.\d+$/)
if (fraction) {
fraction = fraction[0].replace('.', '')
}
let string = ''
while (integer > 0) {
string = String(integer % radix) + string
integer = Math.floor(integer / radix)
}
return fraction ? `${string}.${fraction}` : string
}
document.write(convertNumberToString('100.00148498', 10))
</script>