Win a copy of Micro Frontends in Action this week in the Server-Side JavaScript and NodeJS forum!
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Ron McLeod
• Paul Clapham
• Bear Bibeault
• Junilu Lacar
Sheriffs:
• Jeanne Boyarsky
• Tim Cooke
• Henry Wong
Saloon Keepers:
• Tim Moores
• Stephan van Hulst
• Tim Holloway
• salvin francis
• Frits Walraven
Bartenders:
• Scott Selikoff
• Piet Souris
• Carey Brown

# Convert string to decimal given precisions

Greenhorn
Posts: 4
I need to convert string to decimal value
E.g.
1) Amount: 40976
Precision: 2

Expected output: 409.76

2) 1) Amount: 527
Precision: 3

Expected output: 0.527

Bartender
Posts: 7333
66
You can use String#substring() to get pieces of your original string and concatenate that together with a ".".

What if you have an original String of "42" with a precision of 4? What outcome do you expect?

Rancher
Posts: 3629
40
You can also use Integer.parseInt and Math.pow.  Or, BigInteger and BigDecimal.  Depending on whether you prioritize speed and ease of use, or accuracy.

Carey Brown
Bartender
Posts: 7333
66
What data type do you need the result to be in? String, double, or BigDecimal?

Bhagyashri Mali
Greenhorn
Posts: 4
I expect 0.0042 in case of 42 with 4 precision... actually here precision is indicating the decimal point position

Bhagyashri Mali
Greenhorn
Posts: 4
• 1
I got the solution with Bigdecimal divide method where I also used math.pow() function.
Thanks ðŸ˜Š

Mike Simmons
Rancher
Posts: 3629
40
Cool.  If you're using BigDecimal, I would not use Math.pow since that uses a double and may degrade the accuracy.  And, BigDecimal already has the concept of "scale" which seems to match what you call "precision".  I would do something like this instead:

Bhagyashri Mali
Greenhorn
Posts: 4
Actually that Bigdecimal method don't change the value of that int it just add scale. Here in this case I need to divide that number with power of n(precision) and the final outcome should be Bigdecimal

Bartender
Posts: 4069
156
I'm not sure what you mean. This is what Mikes method does:

 Without subsidies, chem-ag food costs four times more than organic. Or this tiny ad: the value of filler advertising in 2020 https://coderanch.com/t/730886/filler-advertising