Is there a function that can truncate or round a Double? At one point in my code I would like a number like: 1.23456789
to be rounded to 1.23
相关问题
- Unusual use of the new keyword
- Do the Java Integer and Double objects have unnece
- Get Runtime Type picked by implicit evidence
- What's the point of nonfinal singleton objects
- PlayFramework: how to transform each element of a
相关文章
- 关于C#中 float、double、decimal 的运算不精确的问题。
- Gatling拓展插件开发,check(bodyString.saveAs("key"))怎么实现
- RDF libraries for Scala [closed]
- Why is my Dispatching on Actors scaled down in Akk
- How do you run cucumber with Scala 2.11 and sbt 0.
- GRPC: make high-throughput client in Java/Scala
- How can I convert a OLE Automation Date value to a
- Rounding decimals in nested data structures in Pyt
A bit strange but nice. I use String and not BigDecimal
Edit: fixed the problem that @ryryguy pointed out. (Thanks!)
If you want it to be fast, Kaito has the right idea.
math.pow
is slow, though. For any standard use you're better off with a recursive function:This is about 10x faster if you're within the range of
Long
(i.e 18 digits), so you can round at anywhere between 10^18 and 10^-18.For those how are interested, here are some times for the suggested solutions...
Truncation is the fastest, followed by BigDecimal. Keep in mind these test were done running norma scala execution, not using any benchmarking tools.
You may use implicit classes:
Since no-one mentioned the
%
operator yet, here comes. It only does truncation, and you cannot rely on the return value not to have floating point inaccuracies, but sometimes it's handy:Here's another solution without BigDecimals
Truncate:
Round:
Or for any double n and precision p:
Similar can be done for the rounding function, this time using currying:
which is more reusable, e.g. when rounding money amounts the following could be used: