Add number` string-like (`1+1` = `11`)

153 Views Asked by At

I'm making a calculator operating system for a proof of concept Rust OS. I've dug myself into a sort of deep hole with how I handle math, but I don't want to have to rework it all. I have 2 numbers (they are technically f64s but will never have a floating point) and I need to add them Javascript style (1 + "1" = 11). This is all in a #![no_std] environment so I can't use something like format!() or even owned Strings as I have no allocator.

Rust isn't JS so I can't 1 + "1" and obviously + is a binary operation.

Edit: I ended up using the arrayvec library as suggested in How to format output to a byte array with no_std and no allocator?

2

There are 2 best solutions below

0
On

Convert the numbers to integers, then count the number of times you need to divide b by 10 until you reach 0 and multiply a by 10 this same number of times:

fn concat (a: f64, b: f64) -> f64 {
    let mut a = a as u64;
    let b = b as u64;
    let mut c = b;
    while c > 0 {
        a *= 10;
        c /= 10;
    }
    (a+b) as f64
}

Playground

2
On

You can multiply the first number by 10 to the power of the number of digits of the second number. Something like this should do it:

fn concat(a: f64, b: f64) -> f64 {
    a * 10f64.powf(b.log10().floor() + 1.0) + b
}