Search code examples
javascriptstringintegernumbersrounding

Join two numbers to create a new number composed of integer and decimal part


I have two numbers and I need to convert them into a number composed of an integer part and a decimal part.

I'm having problems because the number that represents the integer part can be 0 or -0

I thought of something like that but the result still doesn't get the 0 sign. I thought of using Math.sign but it returns 0 if it's 0 or -0.

const i = -0
const f = 20

const value = parseFloat(i.toString() + "." + f.toString())

console.log(value)

Solution

  • in js this is expected

    // Positive and negative zero are equal to each other in JavaScript:
    console.log(+0 === -0) // true
    console.log(+0 == -0) // true
    
    // Note that +0 is the same as 0:
    console.log(+0) // 0
    console.log(0 === -0) // true
    console.log(0 == -0) // true
    

    This behavior comes from ECMAScript section 7.2.13

    So to differentiate you should use Object.is: (ES6+)

    console.log(+0 === -0) // true
    console.log(Object.is(+0,-0)) // false
    
    
    function makeN(i,f){
        return  (i + f / 100) * (Object.is(i,-0)?-1:1);
    }
    
    console.log(makeN(-0,20)); //-0.20
    console.log(makeN(0,20)); //0.20
    
    

    Using ES5 or below you can use -Infinity as 1/-0 produce -Infinity

    console.log(1/-0) // -Infinity
    console.log(1/-0 === -Infinity) // true
    
    function makeN(i,f){
        return  (i + f / 100) * (1/i === -Infinity?-1:1);
    }
    
    console.log(makeN(-0,20)); //-0.20
    console.log(makeN(0,20)); //0.20
    

    A solution not limited to 2 decimal place Using jsbench.me, toString + parseFloat is like 93% slower than the following solution

    function makeN(i,f){
        return  (i + f / (Math.pow(10,f.toString().length))) * (Object.is(i,-0)?-1:1);
    }