How to convert numbers to words in rust

what should i do so that i can get it for any 4 digit numbers

fn main() {
    use std::iter::successors;

const ONES: [&str; 20] = [
    "zero",
    "one",
    "two",
    "three",
    "four",
    "five",
    "six",
    "seven",
    "eight",
    "nine",
    "ten",
    "eleven",
    "twelve",
    "thirteen",
    "fourteen",
    "fifteen",
    "sixteen",
    "seventeen",
    "eighteen",
    "nineteen",
];
const TENS: [&str; 10] = [
    "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty",
    "seventy", "eighty", "ninety",
];

pub fn encode(num: u64) -> String {
    match num {
        0..=19 => ONES[num as usize].to_string(),
        20..=99 => {
            let upper = (num / 10) as usize;
            match num % 10 {
                0 => TENS[upper].to_string(),
                lower => format!("{}-{}", TENS[upper], encode(lower)),
            }
        }
        100..=999 => format_num (num, 100, "hundred"),
         {
           let (div, order) =
                successors(Some(1u64), |v| v.checked_mul(1000))
                    .zip(ORDERS.iter())
                    .find(|&(e, _)| e > num / 1000)
                    .unwrap();

            format_num(num, div, order)
           
        }
        
    }
    
}

}

facing an error that format num is out of scope

What do you want to print on the number 1234? Also, do you need to print number: 6 in this example?

no. here i limited to use them for a defined values.
i want to know how i can make a code work for a 4 digit number.
i solved it in c++, need to know how to solve it in rust

How did you do it in C++? Probably the same approach could work in Rust as well.

You’d need to convert the number into 4 digits first, then connect them up appropriately into words. Is this a programming exercise or do you just want something that works? If it’s the latter, you could also consider using an existing crate, e.g. https://crates.io/crates/english-numbers, but that may be overkill as it supports arbitrarily large 64-bit numbers.

If you need help adapting the C++ solution to Rust, feel free to share your C++ code and perhaps tell us which parts you don't know how to adapt properly.

ive shared the aproach i had in rust towards this..

Looks like you’ve only partially copied the answer of How to transform a Rust number into English words, like 1 -> "one"? - Stack Overflow now?

1 Like

i guess u can actually see the difference in code

If you’re interested, I gave this a go (printing numbers up to 9999) and produced an implementation that uses enums for an intermediate representation, and involves the fmt::Display trait.

See the code here: Rust Playground

Edit: Fixed a bug that would display e.g. 1200 as ONE THOUSAND TWO HUNDRED ZERO.

1 Like

great one dude.. kudos

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.