截断到小数点后2位而不四舍五入 [英] Truncate to 2 decimal places without rounding

查看:53
本文介绍了截断到小数点后2位而不四舍五入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

找不到或制定出适用于Dart的解决方案.

Can't find or work out a solution to this that works with Dart.

我已经尝试过:
1. toStringAsFixed()-此回合
2. double.parse(number.toStringAsFixed())-此回合
3. num-num%0.01-此回合

I've already tried:
1. toStringAsFixed() - this rounds
2. double.parse(number.toStringAsFixed()) - this rounds
3. num - num % 0.01 - this rounds

我在SO上找到了一些解决方案,但是它们要么使用Flutter/Dart上不提供的功能,要么对我不起作用.

I've found some solutions on SO but they either use functions that aren't available on Flutter/Dart or didn't work for me.

任何帮助将不胜感激.

推荐答案

尝试

double truncateToHundreths(num value) => (value * 100).truncate() / 100;

在某些情况下,您会失去精度,但是这要求您在数字中使用几乎所有53位双精度(当乘以100时会失去精度).

There will be cases where you lose precision, but that requires you to use almost all 53 bits of double precision in the number (when multiplying by 100 loses precision to begin with).

去低谷字符串是一个巨大的开销,如果可能的话,我会避免的,除非您实际上希望以后将数字转换为字符串.

Going trough strings is a significant overhead that I would avoid if possible, unless you actually expect to convert the number to a string anyway afterwards.

这篇关于截断到小数点后2位而不四舍五入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆