- 代码
- 此代码可以实现
整数
和浮点数
之间各进制间的互相转换。
const baseChange = (base, num, tobase) => {
if(typeof(num) === "number") num = num.toString()
let decimal = num.split('.')[1], float10 = 0
if(decimal === undefined) decimal = []
for(let i = 0; i < decimal.length; i++){
float10 += parseInt(decimal[i]) * Math.pow(base, - (i + 1))
}
let int10 = parseInt(num.split('.')[0], base)
return (int10 + float10).toString(tobase)
}
const result1 = baseChange(2, '1010101010110101.01111', 10)
console.log('result1:', result1)
const result2 = baseChange(10, '43701.46875', 2)
console.log('result2:', result2)
const result3 = baseChange(5, '123420113.24122412', 6)
console.log('result3:', result3)
const result4 = baseChange(6, '21004353.3233243140551', 5)
console.log('result4:', result4)
const result5 = baseChange(7, '456311224456', 9)
console.log('result5:', result5)
const result6 = baseChange(9, '26653333277', 7)
console.log('result6:', result6)
- 待改进地方
- 没有校验报错,比如2进制写成121212,这是不可以的,因为2进制数中的数字不可能比2进制还大。
- 二个参数 num 原数据使用number会出现运算错误,这个待改进。