Home > database >  How do I use the "%" math expression?
How do I use the "%" math expression?

Time:03-10

Hi I'm trying to make a calculator app and I want to use the "%" math expression but the result is "Error". How do I solve this?.

...........................................................................................................................................................................................................

enter image description here

...........................................................................................................................................................................................................

This is my code:

String equation = "";
String result = "";
String expression = "";
double equationFontSize = 38.0;
double resultFontSize = 48.0;



buttonPressed(String buttonText) {
setState(() {
  if (buttonText == "AC") {
    equation = "";
    result = "";
    equationFontSize = 38.0;
    resultFontSize = 48.0;
  } else if (buttonText == "⌫") {
    equationFontSize = 48.0;
    resultFontSize = 38.0;
    equation = equation.substring(0, equation.length - 1);
    if (equation == "") {
      equation = "0";
    }
  } else if (buttonText == "=") {
    equationFontSize = 38.0;
    resultFontSize = 48.0;

    expression = equation;
    expression = expression.replaceAll('×', '*');
    expression = expression.replaceAll('÷', '/');
    expression = expression.replaceAll('^', '^');
    expression = expression.replaceAll('%', '%');

    try {
      Parser p = Parser();
      Expression exp = p.parse(expression);
      ContextModel cm = ContextModel();
      result = "${exp.evaluate(EvaluationType.REAL, cm)}";
      _isIntResult();
    } catch (e) {
      result = "Error";
    }
  } else if (buttonText == "⌞⌝") {
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.landscapeLeft]);
  } else {
    equationFontSize = 48.0;
    resultFontSize = 38.0;
    if (equation == "") {
      equation = buttonText;
    } else {
      equation = equation   buttonText;
    }
  }
});
}


_isIntResult() {
if (result.toString().endsWith(".0")) {
  result = int.parse(result.toString().replaceAll(".0", "")).toString();
 }
}

CodePudding user response:

enter image description here

enter image description here

Eg:

10%===>10/100=.1

 100===>10
           

Logic
here /100 - constant 10%======> 10/100=.1 100===> (10/100)*100=10

  var count = text.replaceAll("=", "").replaceAll("", "").split("%");
  if (count.length == 2) {
    if(count[1].isNotEmpty) {
      var s = (int.parse(count[0]) / 100) * int.parse(count[1]);
      setState(() {
        _textcontroller.text = s.toString();
      });
    }else{
      var s = int.parse(count[0]) / 100;
      setState(() {
        _textcontroller.text = s.toString();
      });
    }
  } else if (count.length == 1 ||count.length == 2) {
    var s = int.parse(count[0]) / 100;
    setState(() {
      _textcontroller.text = s.toString();
    });
  }
  

Calculation working here

     void SetMytext(String clickedvalue) {
    var text = _textcontroller.text;
    // var calc = clickedvalue;

    if (clickedvalue == "C") {
      setState(() {
        _textcontroller.text = "";
      });
    } else if (clickedvalue == "=") {
      var count = text.replaceAll("=", "").replaceAll("", "").split("%");
      if (count.length == 2) {
        if(count[1].isNotEmpty) {
          var s = (int.parse(count[0]) / 100) * int.parse(count[1]);
          setState(() {
            _textcontroller.text = s.toString();
          });
        }else{
          var s = int.parse(count[0]) / 100;
          setState(() {
            _textcontroller.text = s.toString();
          });
        }
      } else if (count.length == 1 ||count.length == 2) {
        var s = int.parse(count[0]) / 100;
        setState(() {
          _textcontroller.text = s.toString();
        });
      }
      // setState(() {
      //   _textcontroller.text = text   clickedvalue;
      // });
    } else {
      setState(() {
        _textcontroller.text = text   clickedvalue;
      });
    }
  }

SAmpleCode Dartpad Live Code check

  import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  MyApp({Key? key, this.title}) : super(key: key);
  final String? title;

  @override
  _MyAppState createState() => _MyAppState();
}

var _dropdown1 = "1";
var _textcontroller = TextEditingController();

class _MyAppState extends State<MyApp> {
  int selected = 0;

  @override
  void initState() {
    super.initState();
  }

  var list = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "%", "=", "C"];

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // theme: theme(),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
          appBar: AppBar(),
          body: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: TextFormField(
                  style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
                  textDirection: TextDirection.rtl,
                  controller: _textcontroller,
                ),
              ),
              Flexible(
                // height: 150,
                child: GridView.count(
                  crossAxisCount: 3,
                  mainAxisSpacing: 4,
                  crossAxisSpacing: 4,
                  children: [
                    ...list.map((e) {
                      return ElevatedButton(
                          onPressed: () {
                            SetMytext(e.toString());
                          },
                          child: Text(e.toString()));
                    }).toList()
                  ],
                ),
              )
              // ElevatedButton(onPressed: () {}, child: Text("="))
            ],
          )),
    );
  }

  void SetMytext(String clickedvalue) {
    var text = _textcontroller.text;
    // var calc = clickedvalue;

    if (clickedvalue == "C") {
      setState(() {
        _textcontroller.text = "";
      });
    } else if (clickedvalue == "=") {
      var count = text.replaceAll("=", "").replaceAll("", "").split("%");
      if (count.length == 2) {
        if(count[1].isNotEmpty) {
          var s = (int.parse(count[0]) / 100) * int.parse(count[1]);
          setState(() {
            _textcontroller.text = s.toString();
          });
        }else{
          var s = int.parse(count[0]) / 100;
          setState(() {
            _textcontroller.text = s.toString();
          });
        }
      } else if (count.length == 1 ||count.length == 2) {
        var s = int.parse(count[0]) / 100;
        setState(() {
          _textcontroller.text = s.toString();
        });
      }
      // setState(() {
      //   _textcontroller.text = text   clickedvalue;
      // });
    } else {
      setState(() {
        _textcontroller.text = text   clickedvalue;
      });
    }
  }
}
  • Related