Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete digits after two decimal point without rounding its value in flutter?

Tags:

flutter

dart

var num1 = 10.12345678

What should i do with num1 to delete digits after two decimal point without rounding its value.
I need output as 10.12

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
      title: ' Delete digits after two decimal point ',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: MyHome(),
    ));

class MyHome extends StatefulWidget {
  @override
  _MyHomeState createState() => _MyHomeState();
}

class _MyHomeState extends State<MyHome> {
    @override
  Widget build(BuildContext context) {

    var num1 = 10.12345678;
    print(num1); // I need output as 10.12

    return Container();
  }

}
like image 315
Ishwar Chandra Tiwari Avatar asked Mar 28 '19 21:03

Ishwar Chandra Tiwari


People also ask

How do you get rid of the number after the decimal in flutter?

Use the str() class to convert the decimal to a string. Use the str. rstrip() method to strip the trailing zeros if the number has a decimal point.To remove trailing zeros from a decimal: Use the decimal.

How do you show only 2 digits after the decimal in flutter?

You can use toStringAsFixed in order to display the limited digits after decimal points. toStringAsFixed returns a decimal-point string-representation. toStringAsFixed accepts an argument called fraction Digits which is how many digits after decimal we want to display. Here is how to use it.

How do you remove .0 from a double in flutter?

String formatNumber(double n) { return n. toStringAsFixed(0) //removes all trailing numbers after the decimal. } Save this answer.


1 Answers

If you want to round the number:

var num1 = 10.12345678;
var num2 = double.parse(num1.toStringAsFixed(2)); // num2 = 10.12

If you do NOT want to round the number:

Create this method:

double getNumber(double input, {int precision = 2}) => 
  double.parse('$input'.substring(0, '$input'.indexOf('.') + precision + 1));

Usage:

var input = 113.39999999999999;
var output = getNumber(input, precision: 1); // 113.9
var output = getNumber(input, precision: 2); // 113.99
var output = getNumber(input, precision: 3); // 113.999
like image 116
CopsOnRoad Avatar answered Nov 23 '22 14:11

CopsOnRoad