JS. Представить целое число как дробный остаток?
Первое, что пришло на ум:
function f(int){
return parseFloat("0."+int);
}
Но этот способ довольно медленный. Может есть способ сделать это на уровне битов?
Ответы (1 шт):
Автор решения: Вася Воронцов
→ Ссылка
Предлагаю делить на ближайшее большее число, представимое в виде степени числа 10:
function decPoint(int) {
return int / Math.pow(10, Math.floor(Math.log10(int))+1);
}
Небольшая проверка работоспособности:
function f(int) {
return parseFloat("0."+int);
}
function decPoint(int) {
return int / Math.pow(10, Math.floor(Math.log10(int))+1);
}
let max = 10000000;
function testF() {
let t0 = window.performance.now();
for (let i = 0; i < max; i++) f(i);
console.log("f performance: " + (window.performance.now() - t0) / max);
}
function testDecPoint() {
let t1 = window.performance.now();
for (let i = 0; i < max; i++) decPoint(i);
console.log("decPoint performance: " + (window.performance.now() - t1) / max);
}
testF();
testDecPoint();
let testNums = [5, 55, 555, 123, 1, 10, 100];
for (let tn of testNums) console.log(tn + " => " + decPoint(tn));
Превосходство в производительности для меня составило около 40%:
f performance: 0.00024259000000059603
decPoint performance: 0.0001450699999988079