Search code examples
rustegui

How can I enter decimal numbers in a TextEdit field?


I want to be able to enter decimal numbers in a TextEdit field, but with the following method I can only enter whole numbers:

// value is an f32
let mut value_str = value.to_string();
if ui.text_edit_singleline(&mut value_str).changed() {
    if let Ok(parsed_value) = value_str.parse() {
        value = parsed_value;
    }
}

I´m using egui version 0.27.2


Solution

  • DragValue

    First, what you want might be a DragValue, which allow number input and draging.

    ui.add(egui::DragValue::new(&mut self.f));
    

    Input String

    But if you really want a text field, you might want to set a temp buffer variable for the user input, and change the value on lost_focus

    struct AppState{
        // ...
        f: f32,
        input: String,
        // ...
    }
    
    // inside show()
    if ui.text_edit_singleline(&mut self.input).lost_focus() {
        // if the input value is vaild, update the value
        if let Ok(parsed_value) = self.input.parse() {
            self.f = parsed_value;
        }
        // sync the input value and the value regardless
        self.input = self.f.to_string();
    }