skip to Main Content

I want to add numbers (including negatives) displayed in a column widget.
How to align them with respect to the decimal points?

Any other widget or tricks to align them?

https://ibb.co/d0MhyNV

Thanks.

2

Answers


  1. To align numbers, including negatives, with respect to the decimal points in a column widget, you can use the Text widget along with the TextAlign property. The TextAlign property allows you to control the horizontal alignment of the text within the widget.

    Column(
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        Text('12.34'), // Example positive number
        Text('-56.78'), // Example negative number
        Text('90'), // Example whole number
      ],
    )
    

    Keep in mind that this approach will align the numbers based on the decimal points. If you have numbers with varying decimal places, the decimal points will be aligned, but the whole numbers may not be perfectly aligned

    Example using the Table widget:

    Table(
      children: [
        TableRow(
          children: [
            TableCell(
              child: Text('12.34', textAlign: TextAlign.end),
            ),
          ],
        ),
        TableRow(
          children: [
            TableCell(
              child: Text('-56.78', textAlign: TextAlign.end),
            ),
          ],
        ),
        TableRow(
          children: [
            TableCell(
              child: Text('90', textAlign: TextAlign.end),
            ),
          ],
        ),
      ],
    )
    
    Login or Signup to reply.
  2. you need convert number to string, and split string by decimal points, here is my demo code.

    class _MyHomePageState extends State<MyHomePage> {
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          extendBodyBehindAppBar: true,
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                _numberItemWidget('1'),
                _numberItemWidget('2.1'),
                _numberItemWidget('100'),
                _numberItemWidget('1002.002'),
                _numberItemWidget('-1002.002'),
                _numberItemWidget('+2'),
              ],
            ),
          ),
        );
      }
    
      Widget _numberItemWidget(String number) {
        final strList = number.split('.');
        return Row(
          children: [
            Expanded(
              child: Text(strList[0], textAlign: TextAlign.right,),
            ),
            Text(strList.length > 1 ? '.' : ' '),
            Expanded(
              child: Text(strList.length > 1 ? strList[1] : ''),
            ),
          ],
        );
      }
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search