gpt4 book ai didi

dart - 删除两位小数后的数字而不四舍五入其值?

转载 作者:IT王子 更新时间:2023-10-29 07:07:51 25 4
gpt4 key购买 nike

var num1 = 10.12345678

我应该如何处理 num1 以删除小数点后两位数字而不对其值进行四舍五入。
我需要输出为 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();
}

}

最佳答案

如果要对数字进行四舍五入:

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

如果您不想对数字进行四舍五入:

创建这个方法:

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

用法:

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

关于dart - 删除两位小数后的数字而不四舍五入其值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55407276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com