Ответа на этот вопрос по BigDecimal throws ArithmeticException
public static void main(String[] args) {
int age = 30;
BigDecimal retireMentFund = new BigDecimal("10000.00");
retireMentFund.setScale(2,BigDecimal.ROUND_HALF_UP);
BigDecimal yearsInRetirement = new BigDecimal("20.00");
String name = " Dennis";
for ( int i = age; i <=65; i++){
recalculate(retireMentFund,new BigDecimal("0.10"));
}
BigDecimal monthlyPension = retireMentFund.divide(
yearsInRetirement.divide(new BigDecimal("12"), new MathContext(2, RoundingMode.CEILING)), new MathContext(2, RoundingMode.CEILING));
System.out.println(name+ " will have £" + monthlyPension +" per month for retirement");
}
public static void recalculate (BigDecimal fundAmount, BigDecimal rate){
fundAmount.multiply(rate.add(new BigDecimal("1.00")));
}
Добавить объект MathContext в ваш метод разбора и настроить точность и округление. Это должно решить вашу проблему
Чтобы привязываться к модели на обратной стороне, атрибуты name
элементов управления формы должны соответствовать свойствам модели. Использование цикла foreach
не создает правильные атрибуты имени. Если вы проверите html, вы увидите несколько экземпляров
<input type="text" name="item.LeaveType" .../>
, но для привязки к вашей модели элементы управления должны быть
<input type="text" name="LeaveDetailsList[0].LeaveType" .../>
<input type="text" name="LeaveDetailsList[1].LeaveType" .../>
и т. Д. Самый простой способ подумать об этом - рассмотреть вопрос о том, как вы получите доступ к значению свойства LeaveType
в коде C#
var model = new LeaveBalanceViewModel();
// add some LeaveBalanceDetails instances to the LeaveDetailsList property, then access a value
var leaveType = model.LeaveDetailsList[0].LeaveType;
. Поскольку ваш метод POST будет иметь имя параметра (скажем, model
), просто снимите префикс (model
), и именно так должен быть атрибут имени элемента управления. Для этого вы должны использовать либо цикл for
(сбор должен реализовывать IList<T>
)
for(int i = 0; i < Model.LeaveDetailsList.Count; i++)
{
@Html.TextBoxFor(m => m.LeaveDetailsList[i].LeaveType)
....
}
, либо использовать пользовательский EditorTemplate
(в коллекции необходимо реализовать только IEnumerable<T>
)
В /Views/Shared/EditorTemplates/LeaveBalanceDetails.cshtml
@model yourAssembly.LeaveBalanceDetails
<tr>
<td>@Html.TextBoxFor(m => m.LeaveType)</td>
....
</tr>
, а затем в основном представлении (не в цикле)
<table>
.... // add headings (preferably in a thead element
<tbody>
@Html.EditorFor(m => m.LeaveDetailsList)
</tbody>
</table>
и, наконец, в контроллере
public ActionResult Edit(LeaveBalanceViewModel model)
{
// iterate over model.LeaveDetailsList and save the items
}
Что касается вашего требования, попробуйте это
jQuery(document).on("change", ".DDLChoices", function (e) {
var comma_ChoiceIds = '';
var comma_ChoicesText = '';
$('input[class="DDLChoices"]').each(function (e) {
if (this.checked) {
comma_ChoiceIds = comma_ChoiceIds + $(this).val() + ',';
comma_ChoicesText = comma_ChoicesText + $(this).parent('label').parent() + ',';
}
});
$('#ChoiceIds').val(comma_ChoiceIds);
$('#ChoiceText').val(comma_ChoicesText);
});
@using (Html.BeginForm("Actionname", "Controllername", FormMethod.Post, new { id = "frmChoices" }))
{
@Html.HiddenFor(m => m.ChoiceText, new { @id = "ChoiceText" })
@Html.HiddenFor(m => m.ChoiceIds, new { @id = "ChoiceIds" })
<div class="form-group">
<div>
<table>
<tr>
<th>Name</th>
<th>Selected</th>
</tr>
@foreach (var item in @Model.Choices)
{
<tr>
<td> <label>@item.ChoicesText</label> </td>
<td> <input class="DDLChoices" value="@item.ChoiceIds" type="checkbox" /></td>
</tr>
}
</table>
</div>
<input type="button" value="Submit" onclick="return ChoicesPoster.passChoices()"
</div>
}