❔ Convert decimal without trailing 0s
My goal is to print decimal numbers with all available precision and without a trailing .0
I'd like 123.0 to convert to 123 not 123.0. How can I do this for the decimal type? I was somewhat surprised that 123.0 and 123 are converted into different values.
17 Replies
Samarichitane#3472
REPL Result: Success
Result: bool
Compile: 365.481ms | Execution: 23.164ms | React with ❌ to remove this embed.
Both are decimal
Not the numeric value the value returned by .ToString()
Why you are comparing values with .ToString()
Just use == or .Equals()
My goal is to print decimal numbers with all available precision and without a trailing .0
That's a better explanation
I'm not actually comparing them that's just to show they are diff. I'll edit the Q.
Standard numeric format strings
In this article, learn to use standard numeric format strings to format common numeric types into text representations in .NET.
@jalepi None of these have the desired behavior as far as I can tell
Currency: prints $ so won't work
Decimal: No decimal places I want them all
Exp: Sci notation (no)
FixedPoint: I want varying point based on available precision
General: sci notation (no)
Number: has , separator (even if I remove that with
NumberGroupSeparator=""
it still has fixed precision
Percent: has %
RoundTrip: not supported for decimal
Hex: no
Here's my very unoptimized string munging soln
`As long as i checked it can be done
but i'll be slow af
value.ToString().TrimEnd('0')
, but this (along with your solution) will chop off the 0 in 70
.Oh good point I'll have to revise mine to check for the decimal first
decimal point*
Still would love a native way to either print without .0 or convert 123.0 into 123
brb lunch
Think something like this would do, might have to add or remove a char index
valueText.IndexOf('.') is int i && i >= 0 ? valueText.Substring(0, valueText.IndexOf('0', i)) : valueText
Ultimately going with this
a.ToString("F0") // f zero
dont#0387
REPL Result: Success
Console Output
Compile: 655.541ms | Execution: 39.532ms | React with ❌ to remove this embed.
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.