Today's challenge requires you to create a function that will take a float and return the amount formatted in dollars and cents.
For example:
6.2becomes$6.20
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
This challenge comes from kolohelios on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Oldest comments (24)
Here we go!
And the results:
And how about some
Intl?Which does a bit more, like adding commas:
Hello, I am surprised, you can call a function with ``. How come is it working?
ES6 added this functionality, called Tagged Template! A few examples can be found here: wesbos.com/tagged-template-literals/
Thanks a ton :) learnt new thing
`
love js
Mind rounding "errors":
Same happens in python:
It rounded up, though, so is that an error? It seems like expected behavior to me.
Go - with tests as usual
fun fact - this was the first time I wrote anything using Vim
dollars.go
dollars_test.go
I'm not sure, but I think that "Sprintf" rounds to nearest integer.
Try with a value like 3.149 if still returns 3.14 or 3.15
Yeah it rounds to the nearest cent in this case, the question becomes then do we want it to work that way, or do we say "Hey you don't have a full cent" so it always rounds down?
Added additional test case to clarify current rounding behavior.
Sometimes I just think about Rails method that does a very specific thing, type it out in console and it works
With miles separator too:
Here is the python code
num=float(input())
print("${:,.2f}".format(num))
My take at the challenge written in Haskell.
Try it online.
For some reason, I get imprecise floating point numbers when grabbing the decimal part of a floating point number in Haskell. I'm pretty new to this language so I must miss something. Feel free to improve my work here.
Rust Function:
Elixir:
ruby <3