-2

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?

salmon
  • 31
  • 4
  • 2
    Maybe you can use `write!` like in this question: [How to format output to a byte array with no\_std and no allocator?](https://stackoverflow.com/questions/39488327/how-to-format-output-to-a-byte-array-with-no-std-and-no-allocator) – cafce25 Feb 28 '23 at 00:00

2 Answers2

1

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
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
paholg
  • 1,910
  • 17
  • 19
  • 1
    Both `powf` and `log10` are part of the standard library. – salmon Feb 28 '23 at 00:51
  • If you're on nightly, you can opt-in to core_intrinsics: https://doc.rust-lang.org/beta/core/intrinsics/index.html Otherwise, you could always implement them yourself. – paholg Feb 28 '23 at 02:03
0

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

Jmb
  • 18,893
  • 2
  • 28
  • 55