Six Stars

[resolved] in tJavaRow rounding float to two decimals and use in String

Hi,
Can anybody help me with this: With tJavaRow I'm using code below (simplification of actual use)
output_row.price_ex = (input_row.price/1.21)+" ex vat price"

Challenge: Output has many decimals, but needs to be just two.
FYI: the input is float, the output string
I have read that DecimalFormat might be an approach, unfortunately I am a beginner with Java and Talend so I might need an example what code to use exactly instead of the code above.
Hope someone can help me out
1 ACCEPTED SOLUTION

Accepted Solutions
Six Stars

Re: [resolved] in tJavaRow rounding float to two decimals and use in String

Hi havenderborg

yes.. you need to import java.text.DecimalFormat
or you can do it without any import using math of java
try this
      output_row.price_ex =Math.round((input_row.price/1.21)*100)/100f +" ex vat price"


Just tried the Math.round and that worked, many thanks!
I did notice it didn't have effect if I try that in an expression in tMap (I would still got many decimals), so tJavaRow will solve it for now. (Perhaps I try java.text.DecimalFormat as well later)
5 REPLIES
One Star

Re: [resolved] in tJavaRow rounding float to two decimals and use in String

Try this..
output_row.price_ex =  new DecimalFormat("#.##").format((input_row.price/1.21))+"string";
Six Stars

Re: [resolved] in tJavaRow rounding float to two decimals and use in String

Try this..
output_row.price_ex =  new DecimalFormat("#.##").format((input_row.price/1.21))+"string";


Thanks, tried but results in this error: "DecimalFormat cannot be resolved to a type". When I google for that it seems I need to add code to import DecimalFormat?
Seven Stars

Re: [resolved] in tJavaRow rounding float to two decimals and use in String

output_row.price_ex = new java.text.DecimalFormat("#.##").format(input_row.price/1.21)+"string";
One Star

Re: [resolved] in tJavaRow rounding float to two decimals and use in String

Hi havenderborg

yes.. you need to import java.text.DecimalFormat
or you can do it without any import using math of java
try this
      output_row.price_ex =Math.round((input_row.price/1.21)*100)/100f +" ex vat price"
Six Stars

Re: [resolved] in tJavaRow rounding float to two decimals and use in String

Hi havenderborg

yes.. you need to import java.text.DecimalFormat
or you can do it without any import using math of java
try this
      output_row.price_ex =Math.round((input_row.price/1.21)*100)/100f +" ex vat price"


Just tried the Math.round and that worked, many thanks!
I did notice it didn't have effect if I try that in an expression in tMap (I would still got many decimals), so tJavaRow will solve it for now. (Perhaps I try java.text.DecimalFormat as well later)